c# - 如何更新 Excel VSTO 中 CustomProperties 集合中的值?

标签 c# excel vsto

我正在使用 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/

相关文章:

c# - 如何在 C# 中运行可变数量的并发参数化无限循环类型线程?

C# 导出到 Excel 格式无效

excel - 如何将 Excel 工作表名称传递给 Access 子例程?

c# - 使用 VSTO 将一系列单元格从 excel 复制到 powerpoint

c# - 确定所选电子邮件是来自收件箱还是已发送邮件

c# - 来自Elasticsearch请求的无效NEST响应-无效的文档格式

c# - 可以处理WP7.1 中的所有MouseMove 事件吗?

c# - 导出到 MVC3 ASP.net 中的 excel 文件

email - 从不在 session 帐户中的非默认帐户发送邮件

c# - Excel VSTO -> Hide/Unhide Ribbon Button based on another Ribbon Button 单击