使用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 天的试用许可证

相关推荐
Ray Liang3 小时前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
Scout-leaf3 天前
WPF新手村教程(三)—— 路由事件
c#·wpf
用户298698530143 天前
程序员效率工具:Spire.Doc如何助你一键搞定Word表格排版
后端·c#·.net
mudtools4 天前
搭建一套.net下能落地的飞书考勤系统
后端·c#·.net
玩泥巴的5 天前
搭建一套.net下能落地的飞书考勤系统
c#·.net·二次开发·飞书
唐宋元明清21885 天前
.NET 本地Db数据库-技术方案选型
windows·c#
郑州光合科技余经理5 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
lindexi5 天前
dotnet DirectX 通过可等待交换链降低输入渲染延迟
c#·directx·d2d·direct2d·vortice
feifeigo1235 天前
matlab画图工具
开发语言·matlab
dustcell.5 天前
haproxy七层代理
java·开发语言·前端