我想做的是使用 VSTO 的 C#“Excel 2007 加载项”项目类型为 Excel 创建用户定义函数 (UDF)(因为我只想生成一些通用 UDF)。由于我只是想学习基础知识(无论如何在这个阶段),这就是我的代码的样子:
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Linq;
using Excel = Microsoft.Office.Interop.Excel;
using Office = Microsoft.Office.Core;
using Microsoft.Office.Tools.Excel;
using Microsoft.Office.Tools.Excel.Extensions;
using System.Runtime.InteropServices;
namespace ExcelAddIn1
{
public partial class ThisAddIn
{
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{}
private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
{}
//My UDF
public static double HeronicCal(int a, int b, int c)
{
//first compute S = (a+b+c)/2
double S = (a + b + c) / 2;
double area = Math.Sqrt(S * (S - a) * (S - b) * (S - c));
return area;
}
#region VSTO generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InternalStartup()
{
this.Startup += new System.EventHandler(ThisAddIn_Startup);
this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
}
#endregion
}
}
它编译得很好,当我运行它时,Excel 会弹出一个新的电子表格,当我查看“加载项”列表(在 Excel 选项中)时,我可以在列表中看到我的加载项 (设置为“启动时加载”)。但是我的问题来了,当我尝试从 Excel 中调用我的 UDF 时,Excel 找不到该方法!
我想像的是错误的,我必须将我的方法标记为 Excel UDF(使用方括号——例如在编写 Web 服务时所做的 -> “[WebService]”)。但我一直没能找到这个标签(因为我完全不确定我的直觉是否正确),这就是为什么我决定去找 SO 的好人。
所以我的问题基本上是——从我的代码的角度来看,是否有任何简单的方法可以让 Excel 访问我的 UDF?如果是,如何?
我真的很想留在 VSTO 项目类型(加载项、工作簿、模板)中,因为我当前项目的总体目标是确定使用 VS2010/Excel2007 的 C# UDF 执行是否在可接受的范围内工作速度。为了对此进行测试,我正在使用 Windows7RC 和 VS2010 beta1。
最佳答案
VSTO 不支持创建 Excel UDF。 Automation Add-Ins 可以在 .Net 中创建,并且似乎是 Microsoft 批准的执行方式。
你应该看看 ExcelDna - http://www.codeplex.com/exceldna . ExcelDna 允许托管程序集通过 native .xll 接口(interface)向 Excel 公开用户定义的函数 (UDF) 和宏。该项目是开源的,可以免费用于商业用途。您会发现基于 .Net 的 UDF 的性能类似于 Excel 的 native .xll 加载项。支持大表、长Unicode字符串、多线程重新计算等Excel 2007特性。
使用 ExcelDna,您上面发布的函数将在没有 VSTO 的情况下暴露给 Excel - 您可以将代码放入基于 xml 的 .dna 文件或将其编译为 .dll。
公开您的 UDF 的 .dna 文件如下所示:
<DnaLibrary Language="C#">
using System;
using ExcelDna.Integration;
public class MyFunctions
{
[ExcelFunction(Description="Calculate Stuff", Category="Cool Functions")]
public static double HeronicCal(int a, int b, int c)
{
//first compute S = (a+b+c)/2
double S = (a + b + c) / 2;
double area = Math.Sqrt(S * (S - a) * (S - b) * (S - c));
return area;
}
}
</DnaLibrary>
更新:如今,开始使用 Excel-DNA 的最简单方法是在 Visual Studio 中创建一个新的类库项目,然后从 NuGet 添加“ExcelDna.AddIn”包。这就是一个入门插件 - 只需粘贴您的代码并按 F5 键即可运行。
更新 2: 可能想要查看完整的 working example VSTO + ExcelDna .
关于c# - 如何使用 VSTO 加载项项目轻松创建 Excel UDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/957575/