我正在尝试将自定义属性添加到以编程方式创建的工作簿中。我有一个用于获取和设置属性的方法,但问题是工作簿为 CustomDocumentProperties 属性返回 null。我无法弄清楚如何初始化此属性,以便我可以从工作簿中添加和检索属性。 Microsoft.Office.Core.DocumentProperties 是一个接口,所以我无法执行以下操作
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)
如果您的目标是 .NET 4.0,则可以使用dynamic
后期绑定关键字
Document doc = GetActiveDocument();
if ( doc != null )
{
dynamic properties = doc.CustomDocumentProperties;
foreach (dynamic p in properties)
{
Console.WriteLine( p.Name + " " + p.Value);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)