本文介绍了使用最佳 .NET API 之一从文档中提取文本以提取文档数据的所有必要信息,并指导您如何使用 C#** 从 Word 文档中提取文本。此外,它还提供了配置所需包的信息和一个工作示例,以演示 C# 从 Word 文档中提取文本 应用程序的实现。以下是从 Word 文档中获取文本的关键步骤和示例代码。
使用 C# 从 Word 文档中提取文本的步骤
- 在 .NET 项目中从 NuGet 网站安装 GroupDocs.Parser for .NET 包以从 Word 文档中提取文本
- 添加必要命名空间的引用,以便从 Word 文件中提取文本
- 创建 Parser 类的对象以加载输入 DOCX 文档
- 调用Parser类的GetText方法,得到一个TextReader对象
- 最后,使用 ReadToEnd 方法从 reader 对象中读取文本
以上几点使您能够快速创建应用程序以从 Word 文档 C# 中提取文本。这些步骤不依赖于从文档中提取文本的任何第三方工具,您可以在支持 .NET 环境的任何平台(如 MS Windows、Linux 和 macOS)上使用它们。此外,您必须编写几行代码来使用所需库的几个 API 调用,以便从 DOC 或 DOCX 文档中获取文本。
使用 C# 从 Word 文档中提取文本的代码
using System; | |
using System.Collections.Generic; | |
using System.Text; | |
using System.IO; | |
using GroupDocs.Parser; | |
using GroupDocs.Parser.Data; | |
namespace ExtractTextFromWordDocumentUsingCSharp | |
{ | |
class Program | |
{ | |
public static void Main(string[] args) // Main function to extract text from Word document using C# | |
{ | |
// Remove the watermark in output PDF document by adding license | |
string licensePath = "GroupDocs.Parser.lic"; | |
GroupDocs.Parser.License lic = new GroupDocs.Parser.License(); | |
lic.SetLicense(licensePath); | |
// Create an instance of Parser class | |
using (Parser parser = new Parser("sample.docx")) | |
{ | |
// Extract a text into the reader | |
using(TextReader reader = parser.GetText()) | |
{ | |
// Print a text from the document | |
// If text extraction isn't supported, a reader is null | |
Console.WriteLine(reader == null ? "Text extraction isn't supported" : reader.ReadToEnd()); | |
} | |
} | |
} | |
} | |
} |
read text from Word document C# 功能是在上面的代码片段中开发的,向您展示如何从 DOCX 文档中提取文本。但是,您也可以使用此示例代码中的 DOC 格式文档来获取文本。此外,此示例可适用于从各种其他文档格式中提取文本,包括 DOT、RTF、XLSX、CSV、MHTML、EML、PPTX、ZIP、PDF 等。
我们已经讨论了在 C# 中从 Word 文档中提取文本的过程,并在这篇文章中为其开发了示例代码。最近,我们发表了一篇使用 C# 从 PDF 中提取图像的文章,请查看 如何使用 C# 从 PDF 中提取图像 指南了解更多信息。