C#读取Office文档属性 C#如何获取Word或Excel的作者、标题等信息

来源:这里教程网 时间:2026-02-21 17:41:10 作者:

DocumentFormat.OpenXml
读取 Office 文档属性(推荐)

Office 2007+ 的 .docx 和 .xlsx 文件本质是 ZIP 包,内部包含 XML 元数据,

DocumentFormat.OpenXml
是微软官方、轻量、无需安装 Office 的首选方式。它能直接解析
core.xml
(含作者、标题、创建时间等标准属性)和
app.xml
(含页数、字数等应用属性)。

需安装 NuGet 包:

DocumentFormat.OpenXml
(v2.20+ 支持 .NET 6/7/8)。

关键步骤:

WordprocessingDocument.Open()
SpreadsheetDocument.Open()
打开文件(注意传
false
表示只读)
调用
GetCorePropertiesPart()
获取核心属性部分
CoreProperties
类的属性(如
Creator
Title
LastModifiedBy
)直接读值
若需
Application
Pages
等扩展属性,再通过
GetExtendedPropertiesPart()
加载
ExtendedProperties

示例(Word):

using (var doc = WordprocessingDocument.Open(@"C:\test.docx", false))
{
    var core = doc.CoreFilePropertiesPart?.CoreProperties;
    if (core != null)
    {
        string author = core.Creator?.Text ?? "";
        string title = core.Title?.Text ?? "";
        DateTime? created = core.Created?.Value;
    }
}

Microsoft.Office.Interop
获取完整属性(但有硬依赖)

如果必须读取旧版 .doc/.xls 或需要访问 VBA 属性、自定义文档属性(

CustomDocumentProperties
),只能用 Interop。但它要求目标机器安装对应版本的 Office,且存在 COM 互操作稳定性问题(如进程残留、线程 Apartment 模式错误)。

常见报错:

System.Runtime.InteropServices.COMException: 检索 COM 类工厂中 CLSID 为 … 的组件时失败
,通常因 Office 未安装、位数不匹配(x64 程序调 x86 Office)、或 DCOM 配置异常。

使用前提:

项目引用
Microsoft.Office.Interop.Word
Microsoft.Office.Interop.Excel
启动 Word/Excel 实例时显式设置
Visible = false
DisplayAlerts = false
务必在
finally
中调用
application.Quit()
并释放 COM 对象(
Marshal.ReleaseComObject()
避免在 ASP.NET 或多线程服务中使用——Interop 不是线程安全的

读取自定义文档属性(Custom Properties)的差异处理

标准属性(作者、标题)和自定义属性存储位置不同:前者在 Open XML 的

core.xml
,后者在
custom.xml
(Open XML)或
DocumentProperties
集合(Interop)。漏掉这个区分会导致“明明设置了却读不到”。

Open XML 方式:

调用
mainPart.CustomFilePropertiesPart?.CustomProperties
遍历
CustomProperties.Elements<customproperty>()</customproperty>
,按
Name
属性匹配
值在
property.Value
property.InnerText
中,类型需根据
property.FormatId
判断(如字符串、布尔、日期)

Interop 方式:

Word:
document.CustomDocumentProperties
返回
DocumentProperties
集合
Excel:
workbook.CustomDocumentProperties
注意:某些自定义属性可能被标记为
LinkToContent = true
,此时需先读取关联的书签或单元格内容

兼容性与性能陷阱:.doc vs .docx、.xls vs .xlsx

Open XML 库完全不支持二进制格式(.doc/.xls)。强行用它打开会抛出

FileFormatException
。若必须支持旧格式,只有两个选择:Interop(最稳但重),或第三方库如
NetOffice
(更轻量,仍需 Office)。

性能方面:

Open XML:毫秒级,内存占用低,适合批量处理 Interop:每次启动进程耗时约 300–800ms,且进程常驻风险高;不适合高频、并发场景

一个容易忽略的点:.xlsx 的

Created
时间默认是 UTC,而 .docx 可能是本地时区;读取后建议统一转为
DateTimeKind.Utc
再比较或存储。

相关推荐