使用C#代码向 Word 文档添加文档属性

文档属性(也称为元数据) 是指描述文档的一组信息。所有 Word 文档都自带一组内置的文档属性,包括标题、作者、主题、关键词等。除了内置文档属性之外,Microsoft Word 还允许用户为 Word 文档添加自定义文档属性

在本文中,我们将介绍如何使用 Spire.Doc for .NET ,通过 C# 和 VB.NET 向 Word 文档添加这些文档属性。

安装 Spire.Doc for .NET

首先,你需要将 Spire.Doc for .NET 包中包含的 DLL 文件添加为 .NET 项目的引用。这些 DLL 文件可以通过此链接下载,或通过 NuGet 进行安装。

cs 复制代码
PM> Install-Package Spire.Doc

在 C# 和 VB.NET 中向 Word 文档添加内置文档属性

内置文档属性由名称和值组成。由于其名称是由 Microsoft Word 预先定义的,因此无法设置或更改内置文档属性的名称,但可以设置或修改其对应的值。

示例代码如下:

cs 复制代码
using Spire.Doc;

namespace BuiltinDocumentProperties
{
    class Program
    {
        static void Main(string[] args)
        {
            //创建一个 Document 实例
            Document document = new Document();
            //加载 Word 文档
            document.LoadFromFile("Sample.docx");

            //向文档添加内置文档属性
            BuiltinDocumentProperties standardProperties = document.BuiltinDocumentProperties;
            standardProperties.Title = "添加文档属性";
            standardProperties.Subject = "C# 示例";
            standardProperties.Author = "张三";
            standardProperties.Company = "Eiceblue";
            standardProperties.Manager = "李四";
            standardProperties.Category = "文档操作";
            standardProperties.Keywords = "C#, Word, 文档属性";
            standardProperties.Comments = "本文演示了如何添加文档属性";

            //保存生成的文档
            document.SaveToFile("StandardDocumentProperties.docx", FileFormat.Docx2013);
        }
    }
}

在 C# 和 VB.NET 中向 Word 文档添加自定义文档属性

自定义文档属性可以由文档作者或用户自行定义。每个自定义文档属性都应包含名称、值和数据类型 。数据类型可以是以下四种之一:文本(Text)日期(Date)数字(Number)是/否(Yes or No)

示例代码如下:

cs 复制代码
using Spire.Doc;
using System;

namespace CustomDocumentProperties
{
    class Program
    {
        static void Main(string[] args)
        {
            //创建一个 Document 实例
            Document document = new Document();
            //加载 Word 文档
            document.LoadFromFile("Sample.docx");

            //向文档添加自定义文档属性
            CustomDocumentProperties customProperties = document.CustomDocumentProperties;
            customProperties.Add("Document ID", 1);
            customProperties.Add("Authorized", true);
            customProperties.Add("Authorized By", "John Smith");
            customProperties.Add("Authorized Date", DateTime.Today);

            //保存生成的文档
            document.SaveToFile("CustomDocumentProperties.docx", FileFormat.Docx2013);
        }
    }
}

申请临时许可证

如果您希望移除生成文档中的评估提示信息,或解除功能限制,请为自己申请一个 30 天的试用许可证

相关推荐
加成BUFF2 小时前
Qt开发核心工具:CMake与qmake全面解析
开发语言·qt·cmake·qmake
野生风长2 小时前
从零开始的C语言:文件操作与数据管理(下)(fseek,ftell,rewind,文件的编译和链接)
android·java·c语言·开发语言·visual studio
阿蒙Amon2 小时前
C#每日面试题-属性和字段的区别
开发语言·c#
wuguan_2 小时前
C#之泛型
c#·泛型
bugcome_com2 小时前
深入浅出 C# 索引器:不止于数字索引的灵活利器
c#
2345VOR2 小时前
【ESP32C3接入2025年冬火山大模型教程】
开发语言·数据库·豆包·火山
五阿哥永琪2 小时前
java基础 异常(Exception和Error)
java·开发语言
工程师0072 小时前
C# 调用 Win32 API
开发语言·c#·api·win32
黑头人2 小时前
Error: JAVA_HOME is not set and Java could not be found
java·开发语言