推荐使用 DocumentFormat.OpenXml 读取 Office 2007+ 文档属性,它轻量、无需安装 Office,可解析 core.xml 和 app.xml 中的标准及应用属性;若需支持旧格式或自定义属性,则须用 Interop(需安装 Office)或第三方库。
用 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 配置异常。
使用前提: