使用 C# 从 Excel 文件中删除元数据?

Remove metadata from Excel file using C#?

我目前正在使用 C# 设置多个 excel 文件的自定义属性。我正在使用从 Microsoft 导入的称为 DSOFile 的库来写入 CustomProperties 属性。我 运行 遇到的一个问题是,每当代码尝试写入已写入自定义属性(例如公司和年份)的 excel 文件时,就会抛出 COMException 异常以指示该文件的自定义属性已经有一个同名的字段。确切消息:"An item by that name already exists in the collection"。我希望能够删除集合中的该项目,以便我可以重写文件。例如,如果我不小心将错误的年份添加到文件中的年份属性中,我希望能够清除该字段并向其写入新值。我无法在 DSOFile class 中找到删除元数据的方法。 "programmatically" 是否可以不通过文件属性 window 清除文件中的元数据?

示例代码:

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);

如果您想更改 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);

请注意,您无法通过 dso 中的 CustomProperties 对象更改可通过 SummaryProperties 对象访问的文档的默认属性。 CustomProperties 用于用户使用的其他属性,而不是 Microsoft Office 已经引入的属性。


为了更改自定义属性,您必须知道 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);
}