如何将其转换为自定义excel函数
本文关键字:自定义 excel 函数 转换 | 更新日期: 2023-09-27 18:15:23
我有以下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吗?听起来它可能对你正在尝试做的事情有用。
还有一篇来自Eric Carter的比较老的文章,可能会有所帮助,它使用了一个自动化外接程序。看来你可以做到没有任何第三方库。