C# 使用 Open XML SDK 读取 Word 文件内容
可以使用 Microsoft.Office.Interop.Word 库来读取 Word 文件中的内容,但是这个库只能在 Windows 系统上运行,而且需要安装 Microsoft Office。
另一个选择是使用 Open XML SDK,这个库可以在 Windows、Linux 和 macOS 上运行,而且不需要安装 Microsoft Office。
下面是一个使用 Open XML SDK 读取 Word 文件中内容的示例代码:
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using System.IO;
public static string ReadWordFile(string filePath)
{
using (WordprocessingDocument document = WordprocessingDocument.Open(filePath, false))
{
Body body = document.MainDocumentPart.Document.Body;
return body.InnerText;
}
}
这个方法会返回 Word 文件中的所有文本内容。如果需要进一步处理 Word 文件中的内容,可以使用 Open XML SDK 提供的其他 API 来获取更详细的信息。
原文地址: https://www.cveoy.top/t/topic/nf4b 著作权归作者所有。请勿转载和采集!