簡體   English   中英

如何將其轉換為自定義Excel功能?

[英]how do I turn this into a custom excel function?

我有以下C#代碼,可從數據庫中提取數據並在Excel加載時使用數據填充單元格A1。 我如何將其轉換為自定義函數,從而在用戶鍵入公式(即'= getMyData(“ mycustominput”)')而不是在加載excel時填充該字段?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Excel = Microsoft.Office.Interop.Excel;
using Office = Microsoft.Office.Core;
using Microsoft.Office.Tools.Excel;
using MySql.Data.MySqlClient; 

namespace custom_excel
{
public partial class ThisAddIn
{

    private void ThisAddIn_Startup(object sender, System.EventArgs e)
    {
        Excel.Worksheet activeWorksheet = ((Excel.Worksheet)Application.ActiveSheet);
        Excel.Range firstRow = activeWorksheet.get_Range("A1", missing);
        firstRow.EntireRow.Insert(Excel.XlInsertShiftDirection.xlShiftDown, System.Type.Missing);
        Excel.Range newFirstRow = activeWorksheet.get_Range("A1", missing);

        string connString = "Server=localhost;Port=3306;Database=test;Uid=name;password=password";
        MySqlConnection conn = new MySqlConnection(connString);
        MySqlCommand command = conn.CreateCommand();
        command.CommandText = "SELECT field_value FROM customers LIMIT 1";
        try
        {
            conn.Open();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        MySqlDataReader reader = command.ExecuteReader();
        while (reader.Read())
        {
             newFirstRow.Value2 = reader["field_value"].ToString();
        }

    }

    private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
    {
    }

    private void InternalStartup()
    {
        this.Startup += new System.EventHandler(ThisAddIn_Startup);
        this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
    }
}

}

出門在這里,但是您看過ExcelDNA嗎? 聽起來可能對您要嘗試的操作有用。

還有從埃里克·卡特有些較老的文章,可能是使用的,它使用一個自動化加載項。 看來您可以在沒有任何第三方庫的情況下進行操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM