如何将其转换为自定义Excel功能?

时间:2011-11-22 20:42:08

标签: c# excel

我有以下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);
    }
}

}

1 个答案:

答案 0 :(得分:0)

在这里走出困境,但是你看过ExcelDNA吗?听起来它可能适用于你想要做的事情。

还有一些this来自Eric Carter的旧文章可能有用,它使用自动化插件。看来你可以在没有任何第三方库的情况下完成它。