我正在使用VSTO处理Excel Addon。 我遇到了一个奇怪的问题,如果我尝试从CustomProperties中获取一个值,它会抛出一个COM异常,我不明白为什么。有没有人碰到这个?这是我尝试使用的代码:
CustomProperties properties = worksheet.CustomProperties;
properties.Add("name", "value");
Console.Write(properties["name"]); //this crashes COMException. Type mismatch. (Exception from HRESULT: 0x80020005 (DISP_E_TYPEMISMATCH))
Console.Write(properties[0]); //and this crashes COMException.Exception from HRESULT: 0x800A03EC
Console.Write(properties.Item[0]); //and this also crashes Exception from HRESULT: 0x800A03EC
Console.Write(properties.Item["name"]); //and this crashes as well Type mismatch.
Console.Write(properties.get_Item(0)); //this crashes again HRESULT: 0x800A03EC
Console.Write(properties.get_Item("name"); //and this still crashes Type mismatch.
我不知道如何使用这个系列。我找到了一个解决方法来阅读属性:
Dictionary<string, string> workingProperties = new Dictionary<string, string>();
foreach (dynamic custProp in properties)
workingProperties.Add(custProp.Name, custProp.Value);
string value = workingProperties["name"];// this works
然而,当涉及到更新现有属性时 - 我被卡住了,我需要一种方法来处理该集合中的项目,并且没有删除或删除功能以先删除它然后添加一个名称相同的新文件。
答案 0 :(得分:4)
好的,写这篇文章并实现了一个解决方法:
string GetProperty(Worksheet ws, string name)
{
foreach (CustomProperty cp in ws.CustomProperties)
if (cp.Name == name)
return cp.Value;
return null;
}
void SetProperty(Worksheet ws, string name, string value)
{
bool found = false;
CustomProperties cps = ws.CustomProperties;
foreach (CustomProperty cp in cps)
{
if (cp.Name == name)
{
found = true;
cp.Value = value;
}
}
if (!found)
cps.Add(name, value);
}
然而,非常奇怪的是,无法以正常方式访问该集合。