学习C#调用OpenXml操作word文档的基本用法(9:读取文档基本属性)

WordprocessingDocument类的CoreFilePropertiesPart属性保存文档基本属性,CoreFilePropertiesPart.Features属性集合中保存各类特性实例对象,其中IPackageFeature特性对应的是文档基本属性对象实例。
  使用DocumentFormat.OpenXml.Packaging.IPackageProperties接口对应的实现类保存文档基本属性,该接口中的属性说明如下表所示:

序号 属性名称 说明
1 Title 标题
2 Subject 主题
3 Creator 作者
4 Keywords 标记,关键词
5 Description 备注
6 LastModifiedBy 最后一次保存者
7 Revision 修订号
8 LastPrinted 最后一次打印的时间
9 Created 创建内容的时间
10 Modified 最后一次保存的日期
11 Category 类别
12 Identifier 标识符
13 ContentType 内容类型
14 Language 语言
15 Version 版本号
16 ContentStatus 内容状态

可以采用以下3种方式获取文档基本属性对象:
  1)var pProps = document.PackageProperties;
  2)var pProps = document.CoreFilePropertiesPart.OpenXmlPackage.PackageProperties;
  3)通过document.CoreFilePropertiesPart.Features.FirstOrDefault(r => r.Key.Name == "IPackageFeature")能获取到包含IPackageFeature对象的键值对,但暂时不知道怎么把数据提取出来。
  采用第一种方式打开文档文档,默认的文档基本属性如下所示:

  采用下面的代码修改文档属性,修改后的文档属性如下图所示:

csharp 复制代码
using (WordprocessingDocument document = WordprocessingDocument.Open(txtFilePath.Text, true))
{
    var pProps = document.PackageProperties;
    pProps.Title = "Title:测试标题";
    pProps.Subject = "Subject:测试主题";
    pProps.Creator = "Creator:孙悟空";
    pProps.Keywords = "Keywords:测试,关键词";
    pProps.Description = "Description:测试描述";
    pProps.LastModifiedBy = "LastModifiedBy:牛魔王";
    pProps.Revision = "Revision:测试修订数";
    pProps.LastPrinted = DateTime.Parse("2001-04-01 04:00:00");
    pProps.Created = DateTime.Parse("2000-04-01 04:00:00");
    pProps.Modified = DateTime.Parse("2002-04-01 04:00:00");
    pProps.Category = "Category:测试分类";
    pProps.Identifier = "Identifier:测试标识符";
    pProps.ContentType = "ContentType:测试内容类型";
    pProps.Language = "Language:中文";
    pProps.Version = "Version:测试版本";
    pProps.ContentStatus = "ContentStatus:测试内容状态";
    
    document.Save();
}


参考文献

1\]https://github.com/dotnet/Open-XML-SDK \[2\]https://learn.microsoft.com/zh-cn/office/open-xml/open-xml-sdk \[3\]https://learn.microsoft.com/zh-cn/dotnet/api/documentformat.openxml.wordprocessing.style?view=openxml-3.0.1 \[4\]https://blog.csdn.net/i042416/article/details/126228816

相关推荐
骆驼爱记录5 天前
WPS页码设置:第X页共Y-1页
自动化·word·excel·wps·新人首发
2301_816997885 天前
Word 清除格式的方法
word
微光feng6 天前
毕业论文word引用操作汇总
word·目录·公式·毕业论文·交叉引用·题注
2301_816997886 天前
Word 功能区与快速访问工具栏
word
halen3336 天前
Hellowordl: The Masters Tool for Word Puzzle Enthusiasts
word
lpfasd1236 天前
Markdown 导出 Word 文档技术方案
开发语言·c#·word
Cxiaomu6 天前
Python 文件解析: Excel / Word / PDF 的解析、处理、预览与下载
python·word·excel
bu_shuo6 天前
Word中插入文本内容控件并交叉引用
word·内容控件
缺点内向6 天前
C#中如何创建目录(TOC):使用Spire.Doc for .NET实现Word TOC自动化
c#·自动化·word·.net
2301_816997886 天前
Word 创建打开与保存文档
c#·word·xhtml