学习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();
}


参考文献

1https://github.com/dotnet/Open-XML-SDK

2https://learn.microsoft.com/zh-cn/office/open-xml/open-xml-sdk

3https://learn.microsoft.com/zh-cn/dotnet/api/documentformat.openxml.wordprocessing.style?view=openxml-3.0.1

4https://blog.csdn.net/i042416/article/details/126228816

相关推荐
工具派1 天前
Word文档太大怎么拆分?段落结构与两种拆法的边界实测
开发语言·c#·word
Metaphor6921 天前
Python 实现 Word/TXT 互转:附完整代码
python·word·格式转换·txt
小羊没烦恼!1 天前
【译】利用Asp.net MVC处理文件的上传下载
开发语言·缓存·c#·word·powerpoint·.net
小羊没烦恼!8 天前
微服务化的基石——持续集成
java·大数据·word·powerpoint·.net
Am-Chestnuts8 天前
DeepSeek表格复制到Word变竖线错列?用DS随心转对比几种整理方法
人工智能·word·ds随心转
2501_9307077811 天前
使用C#代码为新创建的 Word 文档创建目录
c#·word
SunnyDays101111 天前
Java 拆分 Word 文档教程:按页、分页符和分节符拆分
java·word·分页·拆分
copilot中国版12 天前
Word Copilot|一键提取文档关键信息,告别逐字阅读
word·copilot
天人合一peng14 天前
西北工业大学校外访问系统
word
古少侠14 天前
deepseek转word工具怎么选?DS随心转与4种方案对比实测
人工智能·word·powerpoint