【发布时间】:2015-11-02 10:56:39
【问题描述】:
我正在尝试在 Visual Studio 2013 中编写 C# 自动化插件。目标是能够从 MS Excel 2013 中调用用 C# 编写的 UDF。我已阅读有关该主题的大部分公开资料,并且尝试改编几个简单的例子,such as。
很遗憾,它们都不是在 VS 2013 和 MSExcel 2013 下编写的。代码示例:
using System;
using System.Net;
using System.Runtime.InteropServices;
using System.Globalization;
using Microsoft.Win32;
namespace MyFirstAddIn
{
// Early binding. Doesn't need AutoDual.
[Guid("5E6CD676-553F-481E-9104-4701C4DAB272")]
[ComVisible(true)]
public interface IFinancialFunctions
{
double Bid(string symbol);
double Ask(string symbol);
double[,] BidnAsk(string symbol, string direction = null);
}
[Guid("B9B7A498-6F84-43EB-A50C-6D26B72895DA")]
[ClassInterface(ClassInterfaceType.None)]
[ComVisible(true)]
public class FinancialFunctions : IFinancialFunctions
{
// Private class members.
private static readonly WebClient webClient = new WebClient();
private const string UrlTemplate = "http://finance.yahoo.com/d/quotes.csv?s={0}&f={1}";
// Private method - data download.
private static double GetDoubleDataFromYahoo(string symbol, string field)
{
string request = string.Format(UrlTemplate, symbol, field);
string rawData = webClient.DownloadString(request);
return double.Parse(rawData.Trim(), CultureInfo.InvariantCulture);
}
// Public "interface" methods.
public double Bid(string symbol)
{
return GetDoubleDataFromYahoo(symbol, "b3");
}
public double Ask(string symbol)
{
return GetDoubleDataFromYahoo(symbol, "b2");
}
public double[,] BidnAsk(string symbol, string direction = null)
{
double bid = GetDoubleDataFromYahoo(symbol, "b3");
double ask = GetDoubleDataFromYahoo(symbol, "b2");
return direction == "v" ? new[,]{{bid}, {ask}} : new[,]{{bid, ask}};
}
[ComRegisterFunctionAttribute]
public static void RegisterFunction(Type type)
{
Registry.ClassesRoot.CreateSubKey(GetSubKeyName(type, "Programmable"));
RegistryKey key = Registry.ClassesRoot.OpenSubKey(GetSubKeyName(type, "InprocServer32"), true);
key.SetValue("",System.Environment.SystemDirectory + @"\mscoree.dll",RegistryValueKind.String);
}
[ComUnregisterFunctionAttribute]
public static void UnregisterFunction(Type type)
{
Registry.ClassesRoot.DeleteSubKey(GetSubKeyName(type, "Programmable"), false);
}
private static string GetSubKeyName(Type type, string subKeyName)
{
System.Text.StringBuilder s = new System.Text.StringBuilder();
s.Append(@"CLSID\{");
s.Append(type.GUID.ToString().ToUpper());
s.Append(@"}\");
s.Append(subKeyName);
return s.ToString();
}
}
}
我已通过以下方式使程序集 COM 可见:
项目->属性->应用程序->程序集信息
我还在“构建”选项卡中注册了 COM 互操作。
构建后,我可以在注册表中看到注册成功并且加载项已在正确的 GUID 下注册。但是,当我打开 Excel 并转到 Developer->Add-ins->Automation 时,我在列表中看不到我的加载项。我验证了我发布的代码适用于 Excel 2010,但由于某种原因,我无法在 Excel 2013 中看到我的加载项。
谁能帮我解决这个问题?
【问题讨论】: