使用 IronWord 从 DOCX 中提取文本
IronWord的ExtractText()方法使您能够通过访问整个文档、特定段落或表格单元格,从DOCX文件中提取文本,为C#中的文档处理和数据分析任务提供了简单的API。
-
1Install IronWord with NuGet Package Manager
-
2复制并运行这段代码。
using IronWord; // Quick example: Extract all text from DOCX WordDocument doc = new WordDocument("sample.docx"); string allText = doc.ExtractText(); Console.WriteLine(allText);C# -
3部署到您的生产环境中进行测试
通过免费试用立即在您的项目中开始使用IronWord
最小工作流程(5 个步骤)
- 安装 IronWord C# 库
- 使用
new WordDocument()加载现有 Word 文档 - 调用文档上的
ExtractText()函数来检索所有文本 - 使用
Paragraphs集合从特定段落中提取文本 - 处理或导出提取的文本内容
如何从 DOCX 文档中提取所有文本?
ExtractText()方法从整个Word文档中检索文本内容。 在这个示例中,我们创建一个新文档,向其中添加文本,使用ExtractText()提取文本,并在控制台中显示它。 这展示了主要的文本提取工作流程。
提取的文本必须保持文档的逻辑阅读顺序。 该方法依次处理标题、段落、列表和其他文本元素,非常适合内容分析和搜索索引应用。
using System;
using IronWord;
// Instantiate a new DOCX file
WordDocument doc = new WordDocument();
// Add text
doc.AddText("Hello, World!");
// Print extracted text from the document to the console
Console.WriteLine(doc.ExtractText());Imports System
Imports IronWord
' Instantiate a new DOCX file
Dim doc As New WordDocument()
' Add text
doc.AddText("Hello, World!")
' Print extracted text from the document to the console
Console.WriteLine(doc.ExtractText())提取的文本是什么样的?

我应该在控制台中期待什么样的输出?

如何从特定段落中提取文本?
为了更好地控制,您可以从特定段落中提取文本,而不是从整个文档中提取。 通过访问Paragraphs集合,您可以定位和处理所需的任意段落。 在处理具有结构化内容的文档或需要独立处理特定部分时,这种细化方法非常有用。
在这个示例中,我们从第一个和最后一个段落中提取文本,组合它们,并将结果保存为.txt文件。这种技术通常用于文档摘要工具中,您可能希望提取文档的介绍和结论。 类似于您可能使用许可证密钥来解锁功能,Paragraphs集合使您可以访问特定的文档元素。
using System.IO;
using System.Linq;
using IronWord;
// Load an existing DOCX file
WordDocument doc = new WordDocument("document.docx");
// Extract text and assign variables
string firstParagraph = doc.Paragraphs[0].ExtractText();
string lastParagraph = doc.Paragraphs.Last().ExtractText();
// Combine the texts
string newText = firstParagraph + " " + lastParagraph;
// Export the combined text as a new .txt file
File.WriteAllText("output.txt", newText);Imports System.IO
Imports System.Linq
Imports IronWord
' Load an existing DOCX file
Dim doc As New WordDocument("document.docx")
' Extract text and assign variables
Dim firstParagraph As String = doc.Paragraphs(0).ExtractText()
Dim lastParagraph As String = doc.Paragraphs.Last().ExtractText()
' Combine the texts
Dim newText As String = firstParagraph & " " & lastParagraph
' Export the combined text as a new .txt file
File.WriteAllText("output.txt", newText)结合文档分析要求,提取特定段落的能力变得非常强大。 例如,您可以根据格式、位置或内容模式提取关键段落。 这种选择性提取方法有助于缩短处理时间,并将重点放在最相关的内容上。
从第一段中提取了哪些内容?

从最后一段中提取了哪些内容?

合并后的文本如何显示在输出文件中?

上面的截图显示了第一段提取、最后一段提取以及保存到文本文件中的合并输出。请注意,提取过程保留了文本内容,同时删除了格式信息,使其适合纯文本处理。
如何从 DOCX 表格中提取数据?
表格通常包含需要提取进行处理或分析的结构化数据。 IronWord 允许您通过浏览行和单元格来访问表格数据。 在这个例子中,我们加载一个包含 API 统计信息的文档,并从第 2 行第 4 列提取一个特定的单元格值。
表格提取对于数据迁移项目、报告生成和自动数据收集工作流至关重要。 处理表格数据时,理解基于零的索引系统至关重要——第一个表是Rows[0]等等。 这种类似于 许可结构的系统化方法提供了可预测的访问模式。
using System;
using IronWord;
using IronWord.Models;
// Load the API statistics document
WordDocument apiStatsDoc = new WordDocument("api-statistics.docx");
// Extract text from the 1st table, 4th column and 3rd row
string extractedValue = ((TableCell)apiStatsDoc.Tables[0].Rows[2].Cells[3]).ExtractText();
// Print extracted value
Console.WriteLine($"Target success rate: {extractedValue}");
代码演示了使用集合属性Cells来访问表格单元格。 注意,((TableCell)cell).ExtractText()。 这需要将using IronWord.Models;添加到您的命名空间声明中。
源表是什么样的?

从表格单元格中获取什么值?

高级文本提取场景
在处理复杂文档时,您可能需要结合多种提取技术。 下面的示例演示了从多个元素中提取文本并进行不同处理的过程:
using IronWord;
using IronWord.Models;
using System.Text;
using System.Linq;
// Load a complex document
WordDocument complexDoc = new WordDocument("report.docx");
// Create a StringBuilder for efficient string concatenation
StringBuilder extractedContent = new StringBuilder();
// Extract and process headers (assuming they're in the first few paragraphs)
var headers = complexDoc.Paragraphs
.Take(3)
.Select(p => p.ExtractText())
.Where(text => !string.IsNullOrWhiteSpace(text));
foreach (var header in headers)
{
extractedContent.AppendLine($"HEADER: {header}");
}
// Extract table summaries
foreach (var table in complexDoc.Tables)
{
// Get first cell as table header/identifier
string tableIdentifier = ((TableCell)table.Rows[0].Cells[0]).ExtractText();
extractedContent.AppendLine($"\nTABLE: {tableIdentifier}");
// Extract key metrics (last row often contains totals)
if (table.Rows.Count > 1)
{
var lastRow = table.Rows.Last();
var totals = lastRow.Cells.Select(cell => ((TableCell)cell).ExtractText());
extractedContent.AppendLine($"Totals: {string.Join(", ", totals)}");
}
}
// Save the structured extraction
System.IO.File.WriteAllText("structured-extract.txt", extractedContent.ToString());
这个高级示例展示了如何通过组合不同的文档元素来创建结构化提取。 这种方法适用于生成文档摘要、创建索引或准备进一步处理的数据。 正如升级可以增强软件功能一样,结合提取方法可以增强您的文档处理能力。
文本提取的最佳实践
在生产应用程序中实施文本提取时,请考虑以下最佳实践:
1.错误处理:始终用 try-catch 块封装提取代码,以处理可能损坏或具有意外结构的文档。
2.性能优化:对于大型文档或批量处理,可考虑只提取必要的部分,而不是整个文档内容。
3.字符编码:保存提取的文本时要注意字符编码,尤其是包含特殊字符或多种语言的文档。
- 内存管理:处理多个文档时,妥善处理
WordDocument对象以防止内存泄漏。
请记住,文本提取会保留逻辑阅读顺序,但会删除格式。 如果您需要维护格式信息,请考虑使用其他IronWord功能或单独存储元数据。 对于生产部署,请查看 更新日志,了解最新功能和改进。
摘要
IronWord的ExtractText()方法提供了一种从DOCX文件中提取文本的强大而灵活的方法。 无论您需要提取整个文档、特定段落还是表格数据,API 都能提供直接的方法来实现您的目标。 通过将这些技术与适当的错误处理和优化策略相结合,您可以构建强大的文档处理应用程序,有效处理各种文本提取场景。
如需了解更高级的应用场景和探索其他功能,请查看 扩展工具 和其他文档资源,以增强您的文档处理能力。
常见问题解答
如何用 C# 从 Word 文档中提取所有文本?
在 WordDocument 对象上使用 IronWord 的 ExtractText() 方法。只需用 WordDocument doc = new WordDocument("document.docx"); 加载 DOCX 文件,然后调用 string text = doc.ExtractText(); 从文件中获取所有文本内容。
我可以从特定段落而不是整个文档中提取文本吗?
是的,IronWord 允许您通过访问段落集合从特定段落中提取文本。使用 doc.Paragraphs[index].ExtractText() 针对单个段落进行更精细的文本提取。
如何从 DOCX 文件的表格中提取文本?
IronWord 可通过 Tables 集合提取表格文本。使用 doc.Tables[0].Rows[0].Cells[0].ExtractText() 访问特定单元格,即可检索文档中任何表格单元格的文本内容。
using ExtractText() 时,提取的文本按照什么顺序排列?
IronWord 的 ExtractText() 方法可以保持文档的逻辑阅读顺序,依次处理标题、段落、列表和其他文本元素,是内容分析和搜索索引的理想选择。
开始从 DOCX 文件中提取文本的基本步骤是什么?
首先通过 NuGet 安装 IronWord(Install-Package IronWord),然后创建或加载 WordDocument,最后使用 ExtractText() 方法根据需要从整个文档、特定段落或表格单元格中获取文本。
文本提取是否适合构建文档索引系统?
是的,IronWord 的文本提取功能非常适合构建文档索引系统、内容管理解决方案和数据提取管道,提供对 Word 文档内容的高效编程访问。
How can I export extracted text to a file using IronWord?
Once you've extracted the text, you can use C# file handling methods like `File.WriteAllText` to save the text to a file, as demonstrated in the tutorial with paragraph extraction where combined text is saved to an output.txt file.
Is it possible to extract introduction and conclusion sections separately?
Yes, you can extract specific paragraphs such as the introduction and conclusion by targeting them within the `Paragraphs` collection. This method is effective for document summarization tools requiring distinct extraction of key sections.
What encoding considerations should be taken when saving extracted text?
IronWord users should be aware of character encoding, especially when dealing with documents containing special characters or multiple languages. Ensuring the correct encoding is crucial when saving extracted text to maintain text integrity.
How can IronWord's text extraction be optimized for large documents?
For large documents, optimize text extraction by targeting only the necessary portions instead of extracting the entire content. This ensures efficiency, reduces processing time, and leverages the full capabilities of IronWord.
