讀取和寫入檔案屬性

文件屬性可與文件一起儲存。 Office 應用程式提供許多內建屬性,例如作者、標題和主旨。 本主題說明如何設定 Microsoft Office Excel 和 Microsoft Office Word 的文件屬性。

適用於: 本主題中的資訊適用於下列應用程式的檔層級專案和 VSTO 載入宏專案:Excel;幻燈片;專案;詞。 如需詳細資訊,請參閱 Office 應用程式 lication 和項目類型所提供的功能。

在 Excel 中設定文件屬性

若要處理 Excel 的內建屬性,請使用下列屬性:

  • 在文件層級專案中,使用 BuiltinDocumentProperties 類別的 ThisWorkbook 屬性。

  • 在 VSTO 增益集專案中,則請使用 BuiltinDocumentProperties 物件的 Workbook 屬性。

    這些屬性會傳回 DocumentProperties 物件,它是 DocumentProperty 物件的集合。 您可以按照名稱或集合內的索引,使用該集合的 Item 屬性擷取特定的屬性。

    下列程式碼範例說明如何變更文件層級專案的內建 Revision Number 屬性。

變更 Excel 的修訂編號屬性

  1. 將內建的文件屬性指派給變數。

    Microsoft.Office.Core.DocumentProperties properties;
    
    properties = (Microsoft.Office.Core.DocumentProperties)
        Globals.ThisWorkbook.BuiltinDocumentProperties; 
    
    Microsoft.Office.Core.DocumentProperty prop;
    prop = properties["Revision Number"];
    
  2. 遞增 Revision Number 屬性,數目為一。

    if (prop.Value == null)
    {
        prop.Value = 1;
    }
    else
    {
        int revision;
        if (int.TryParse((string)prop.Value, out revision))
        {
            prop.Value = revision + 1;
            MessageBox.Show("Revision Number = " + revision);
        }
        else
        {
            MessageBox.Show("Revision Number = invalid value");
        }
    }
    

在 Word 中設定文件屬性

若要處理 Word 的內建屬性,請使用下列屬性:

  • 在文件層級專案中,使用 BuiltInDocumentProperties 類別的 ThisDocument 屬性。

  • 在 VSTO 增益集專案中,則請使用 BuiltInDocumentProperties 物件的 Document 屬性。

    這些屬性會傳回 DocumentProperties 物件,它是 DocumentProperty 物件的集合。 您可以按照名稱或集合內的索引,使用該集合的 Item 屬性擷取特定的屬性。

    下列程式碼範例說明如何變更文件層級專案的內建 Subject 屬性。

變更主旨屬性

  1. 將內建的文件屬性指派給變數。

    Microsoft.Office.Core.DocumentProperties properties;
    
    properties = (Microsoft.Office.Core.DocumentProperties)
        Globals.ThisDocument.BuiltInDocumentProperties;
    
  2. Subject 屬性變更成「白皮書」。

    // Set the Subject property. 
    properties["Subject"].Value = "Whitepaper";
    

穩固程式設計

此範例假設,在 Excel 文件層級專案的 ThisWorkbook 類別和 Word 文件層級專案的 ThisDocument 類別中,您已經撰寫了程式碼。

雖然您處理的是 Word 和 Excel 及其物件,但 Microsoft Office 仍會提供可用的內建文件屬性清單。 嘗試存取未定義的屬性會引發例外狀況。