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

上一篇文章中介绍的CoreFilePropertiesPart类保存Word文档的核心属性,除此之外,ExtendedFilePropertiesPart类保存Word文档的扩展属性,CustomFilePropertiesPart类保存自定义属性,本文学习后面2种类型的数据读取方式。

读取扩展属性

Word文档的扩展属性值具体保存在ExtendedFilePropertiesPart类的Properties属性中,后者类型为DocumentFormat.OpenXml.ExtendedProperties.Properties,其主要属性如下表所示(主要展示word文档的扩展属性,其它文档格式的扩展属性没有列出,有需要的请在参考文献3中查询):

序号 属性名称 说明
1 Application 程序名称
2 ApplicationVersion 程序版本号
3 Company 公司名称
4 Characters 字符数
5 CharactersWithSpaces 字符数(含空格)
6 DigitalSignature 数字签名
7 DocumentSecurity 文档安全性
8 HyperlinkList 超链接列表
9 Lines 行数
10 LinksUpToDate 是否最新链接
11 Manager 经理
12 Pages 总页数
13 Paragraphs 段落数
14 Words 字数
15 ScaleCrop 比例
16 Template 文档模板名称
17 TotalTime 总编辑时间

扩展属性读取示例及word文档中的扩展属性截图如下所示:

csharp 复制代码
using (WordprocessingDocument document = WordprocessingDocument.Open(txtFilePath.Text, false))
{
    StringBuilder sbInfo=new StringBuilder();
    ExtendedFilePropertiesPart ePart = document.ExtendedFilePropertiesPart;
    if(ePart != null && ePart.Properties!=null)
    {
        sbInfo.AppendLine("文档模板名称:" + ePart.Properties.Template.InnerText);
		...
		...
    }
}
读取自定义属性

Word文档的自定义属性值具体保存在CustomFilePropertiesPart类的Properties属性中,后者类型为DocumentFormat.OpenXml.CustomProperties.Properties,扩展属性值列表通过调用Elements<CustomDocumentProperty>函数获取,CustomDocumentProperty类最重要的字段是自定义属性名称Name、自定义属性值InnerText。
  通常Word文档中没有自定义属性,可以打开word文档,点击"文件"菜单下的信息子菜单,然后点击右侧的属性文本,在弹出的属性窗口中切换到自定义页签以设置自定义名称及值。

  下面的代码用于读取Word文档中的自定义属性列表:

csharp 复制代码
StringBuilder sbInfo=new StringBuilder();
CustomFilePropertiesPart cPart = document.CustomFilePropertiesPart;
if(cPart != null && cPart.Properties!=null)
{
    foreach (CustomDocumentProperty property in cPart.Properties.Elements<CustomDocumentProperty>())
    {
        if (string.IsNullOrEmpty(property.Name))
        {
            continue;
        }
        
        sbInfo.AppendLine($"{property.Name}:{property.InnerText}");
    }

    MessageBox.Show(sbInfo.ToString());
}

参考文献

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

相关推荐
E_ICEBLUE17 小时前
在 Python 中对比 Word 文档:自动生成修订报告
python·word
大模型RAG和Agent技术实践17 小时前
破译Word文档的“语义黑盒”:企业级DOCX RAG架构演进与全链路实战(完整源代码)
人工智能·架构·大模型·word·智能问答·rag
superior tigre19 小时前
word参考文献交叉引用的方法(包括批量把交叉引用改为上标、保留跳转功能到pdf)
word
我喜欢就喜欢20 小时前
Word 模板匹配与样式同步技术详解
开发语言·c++·qt·word·模板匹配
拾穗哥1 天前
wps/word行距不正常调整
word·wps
重生之光头强下海当程序猿2 天前
调整word中的序号格式(缩进,起始值,序号与文字的间距等
前端·css·word
Eiceblue3 天前
C# 中如何设置 Word 文档页面?(页面大小、边距、方向自动化控制)
c#·自动化·word·visual studio
热爱生活的五柒4 天前
Word 论文里参考文献经常在修改后错乱,如何解决
word
醉酒柴柴4 天前
word创建样式以后应用于所有新文件
开发语言·学习·c#·word
珞瑜·4 天前
Windows版Word如何启用保存时自动删除个人信息
word