我目前正在使用C#设置多个excel文件的自定义属性。我正在使用从微软导入的称为DSOFile的库来写入CustomProperties属性。我遇到的一个问题是,每当代码试图写入已写入自定义属性的excel文件(如“公司”和“年”)时,就会抛出一个COMException异常,以指示该文件的自定义属性已经具有该名称的字段。确切消息:“集合中已经存在以该名称命名的项”。我希望能够删除集合中的该项,以便可以重写到文件中。例如,如果我不小心在文件中添加了错误的年份属性,我希望能够清除该字段并为其编写一个新的值。我无法在DSOFile类中找到删除元数据的方法。是否可以“以编程方式”清除文件中的元数据,而无需通过“文件属性”窗口进行操作?
样本代码:
DSOFILE.OleDocumentProperties dso = new DSOFile.OleDocumentProperties();
dso.Open(@"c\temp\test.xls", false, DSOFile.dsoFileOpenOptions.dsoOptionDefault);
//add metadata
dso.CustomProperties.Add("Company", "Sony");
dso.Save();
dso.Close(false);发布于 2016-03-25 20:49:15
如果要更改Office或Author Office使用的默认属性,只需通过SummaryProperties对象更新它们:
OleDocumentProperties dso = new DSOFile.OleDocumentProperties();
dso.Open(@"c:\temp\test.xls", false, DSOFile.dsoFileOpenOptions.dsoOptionDefault);
//Update Company
dso.SummaryProperties.Company = "Hello World!";
dso.Save();
dso.Close(false);请注意,您不能更改文档的默认属性,您可以通过SummaryProperties对象访问dso中的CustomProperties对象。CustomProperties用于用户使用的其他属性,而不是Microsoft已经引入的属性。
为了更改自定义属性,您必须知道CustomProperties是一个可以通过foreach迭代的集合。因此,您可以使用以下两种方法:
private static void DeleteProperty(CustomProperties properties, string propertyName)
{
foreach(CustomProperty property in properties)
{
if (string.Equals(property.Name, propertyName, StringComparison.InvariantCultureIgnoreCase))
{
property.Remove();
break;
}
}
}
private static void UpdateProperty(CustomProperties properties, string propertyName, string newValue)
{
bool propertyFound = false;
foreach (CustomProperty property in properties)
{
if (string.Equals(property.Name, propertyName, StringComparison.InvariantCultureIgnoreCase))
{
// Property found, change it
property.set_Value(newValue);
propertyFound = true;
break;
}
}
if(!propertyFound)
{
// The property with the given name was not found, so we have to add it
properties.Add(propertyName, newValue);
}
}下面是一个关于如何使用UpdateProperty的示例:
static void Main(string[] args)
{
OleDocumentProperties dso = new DSOFile.OleDocumentProperties();
dso.Open(@"c:\temp\test.xls", false, DSOFile.dsoFileOpenOptions.dsoOptionDefault);
UpdateProperty(dso.CustomProperties, "Year", "2017");
dso.Save();
dso.Close(false);
}https://stackoverflow.com/questions/36225881
复制相似问题