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