簡體   English   中英

使用 C# 從 Excel 文件中刪除元數據?

[英]Remove metadata from Excel file using C#?

我目前使用 C# 來設置多個 excel 文件的自定義屬性。 我正在使用從 Microsoft 導入的稱為 DSOFile 的庫來寫入 CustomProperties 屬性。 我遇到的一個問題是,每當代碼嘗試寫入已寫入自定義屬性(例如 Company 和 Year)的 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);

如果您想更改 Office 使用的默認屬性,如 Company 或 Author,您可以通過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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM