我试图将自定义属性添加到我以编程方式创建的工作簿。我有一个方法来获取和设置属性,但问题是工作簿正在为CustomDocumentProperties属性返回null。我无法弄清楚如何初始化此属性,以便我可以从工作簿中添加和检索属性。 Microsoft.Office.Core.DocumentProperties是一个接口,所以我不能去,然后执行以下以编程方式访问Excel自定义文档属性
if(workbook.CustomDocumentProperties == null)
workbook.CustomDocumentProperties = new DocumentProperties;
这里是我得和设置属性代码:
private object GetDocumentProperty(string propertyName, MsoDocProperties type)
{
object returnVal = null;
Microsoft.Office.Core.DocumentProperties properties;
properties = (Microsoft.Office.Core.DocumentProperties)workBk.CustomDocumentProperties;
foreach (Microsoft.Office.Core.DocumentProperty property in properties)
{
if (property.Name == propertyName && property.Type == type)
{
returnVal = property.Value;
}
DisposeComObject(property);
}
DisposeComObject(properties);
return returnVal;
}
protected void SetDocumentProperty(string propertyName, string propertyValue)
{
DocumentProperties properties;
properties = workBk.CustomDocumentProperties as DocumentProperties;
bool propertyExists = false;
foreach (DocumentProperty prop in properties)
{
if (prop.Name == propertyName)
{
prop.Value = propertyValue;
propertyExists = true;
}
DisposeComObject(prop);
if(propertyExists) break;
}
if (!propertyExists)
{
properties.Add(propertyName, false, MsoDocProperties.msoPropertyTypeString, propertyValue, Type.Missing);
}
DisposeComObject(propertyExists);
}
线 性质= workBk.CustomDocumentProperties作为DocumentProperties; 总是将属性设置为null。
这是使用Microsoft.Office.Core v12.0.0.0和Microsoft.Office.Interop.Excell v12.0.0.0(Office 2007中)
准确地说,我找到了这个链接,并且当您发布此内容时我发布了我的代码。 +1并接受为您:-) – 2009-07-16 14:18:46
更新以链接“为什么”:https://support.microsoft.com/zh-cn/kb/303296 – 2016-02-09 18:18:37