创建和修改自定义文档属性

上面列出的 Microsoft Office 应用程序提供与文档存储在一起的内置属性。 此外,如果要将其他信息与文档一起存储,可以创建和修改自定义文档属性。

适用于: 本主题中的信息适用于以下应用程序的文档级项目和 VSTO 外接程序项目: Excel;幻灯片;项目;词。 有关详细信息,请参阅办公室应用程序和项目类型提供的功能。

使用文档的 CustomDocumentProperties 属性来处理自定义属性。 例如,在 Microsoft Office Excel 的文档级项目中,请使用 CustomDocumentProperties 类的 ThisWorkbook 属性。 在 Excel 的 VSTO 外接程序项目中,请使用 CustomDocumentProperties 对象的 Workbook 属性。 这些属性将返回 DocumentProperties 对象,该对象为 DocumentProperty 对象的集合。 可以使用集合的 Item 属性,按名称或索引检索该集合中的特定属性。

下面的示例演示如何在 Excel 文档级自定义项中添加自定义属性并为其赋值。

示例

void TestProperties()
{
    Microsoft.Office.Core.DocumentProperties properties;
    properties = (Office.DocumentProperties)this.CustomDocumentProperties;

    if (ReadDocumentProperty("Project Name") != null)
    {
        properties["Project Name"].Delete();
    }

    properties.Add("Project Name", false,
        Microsoft.Office.Core.MsoDocProperties.msoPropertyTypeString,
        "White Papers");
}

private string ReadDocumentProperty(string propertyName)
{
    Office.DocumentProperties properties;
    properties = (Office.DocumentProperties)this.CustomDocumentProperties;

    foreach (Office.DocumentProperty prop in properties)
    {
        if (prop.Name == propertyName)
        {
            return prop.Value.ToString();
        }
    }
    return null;
}

可靠编程

尝试访问未定义的属性的 Value 属性会引发异常。