我正在使用 VSTO 开发 Excel 插件。 我刚刚遇到一个奇怪的问题,如果我尝试从 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
但是,当涉及到更新现有属性时 - 我陷入困境,我需要一种方法来处理该集合中的项目,并且没有“删除”或“删除”功能来首先删除它,然后使用同名。
最佳答案
好的,正在写这篇文章并实现了一个解决方法:
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);
}
仍然很奇怪,无法以正常方式访问该集合。
关于c# - 如何更新 Excel VSTO 中 CustomProperties 集合中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28490255/