使用 IronWord 从 DOCX 中提取文本
IronWord 的 ExtractText() 方法允许您通过访问整个文档、特定段落或表格单元格来从 DOCX 文件中提取文本,为 C# 中的文档处理和数据分析任务提供了一个简单的 API。
快速入门:从 DOCX 中提取文本
-
使用 NuGet 包管理器安装 https://www.nuget.org/packages/IronWord
PM > Install-Package IronWord -
复制并运行这段代码。
using IronWord; // Quick example: Extract all text from DOCX WordDocument doc = new WordDocument("sample.docx"); string allText = doc.ExtractText(); Console.WriteLine(allText); -
部署到您的生产环境中进行测试
通过免费试用立即在您的项目中开始使用IronWord
最小工作流程(5 个步骤)
- 安装 IronWord C# 库
- 使用 `new WordDocument()` 加载现有 Word 文档
- 调用文档上的`ExtractText()`函数来检索所有文本
- 使用`Paragraphs`集合从特定段落中提取文本
- 处理或导出提取的文本内容
如何从 DOCX 文档中提取所有文本?
ExtractText() 方法可从整个 Word 文档中提取文本内容。 在此示例中,我们将创建一个新文档,向其中添加文本,使用 ExtractText() 提取该文本,并将其显示在控制台中。 这展示了主要的文本提取工作流程。
提取的文本必须保持文档的逻辑阅读顺序。 该方法依次处理标题、段落、列表和其他文本元素,非常适合内容分析和搜索索引应用。
:path=/static-assets/word/content-code-examples/how-to/extract-text-simple.cs
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 集合可让您访问特定的文档元素。
:path=/static-assets/word/content-code-examples/how-to/extract-text-paragraphs.cs
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 列提取一个特定的单元格值。
表格提取对于数据迁移项目、报告生成和自动数据收集工作流至关重要。 处理表格数据时,理解基于零的索引系统至关重要——第一张表格为 Tables[0],第一行是 Rows[0],以此类推。 这种类似于 许可结构的系统化方法提供了可预测的访问模式。
:path=/static-assets/word/content-code-examples/how-to/extract-text-table.cs
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 2nd row
string extractedValue = ((TableCell)apiStatsDoc.Tables[0].Rows[2].Cells[3]).ExtractText();
// Print extracted value
Console.WriteLine($"Target success rate: {extractedValue}");
Imports System
Imports IronWord
Imports IronWord.Models
' Load the API statistics document
Dim apiStatsDoc As New WordDocument("api-statistics.docx")
' Extract text from the 1st table, 4th column and 2nd row
Dim extractedValue As String = CType(apiStatsDoc.Tables(0).Rows(2).Cells(3), TableCell).ExtractText()
' Print extracted value
Console.WriteLine($"Target success rate: {extractedValue}")
该代码演示了如何使用集合属性 Rows 和 Cells 访问表格单元格。 请注意,Cells 集合返回 ITableCell 接口对象,必须将其强制转换为 TableCell 才能调用 ExtractText 方法:((TableCell)cell).ExtractText()。 这需要在您的命名空间声明中添加 using IronWord.Models;。
源表是什么样的?
从表格单元格中获取什么值?
高级文本提取场景
在处理复杂文档时,您可能需要结合多种提取技术。 下面的示例演示了从多个元素中提取文本并进行不同处理的过程:
using IronWord;
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 = 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 => cell.ExtractText());
extractedContent.AppendLine($"Totals: {string.Join(", ", totals)}");
}
}
// Save the structured extraction
System.IO.File.WriteAllText("structured-extract.txt", extractedContent.ToString());
using IronWord;
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 = 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 => cell.ExtractText());
extractedContent.AppendLine($"Totals: {string.Join(", ", totals)}");
}
}
// Save the structured extraction
System.IO.File.WriteAllText("structured-extract.txt", extractedContent.ToString());
Imports IronWord
Imports System.Text
Imports System.Linq
' Load a complex document
Dim complexDoc As New WordDocument("report.docx")
' Create a StringBuilder for efficient string concatenation
Dim extractedContent As New StringBuilder()
' Extract and process headers (assuming they're in the first few paragraphs)
Dim headers = complexDoc.Paragraphs _
.Take(3) _
.Select(Function(p) p.ExtractText()) _
.Where(Function(text) Not String.IsNullOrWhiteSpace(text))
For Each header In headers
extractedContent.AppendLine($"HEADER: {header}")
Next
' Extract table summaries
For Each table In complexDoc.Tables
' Get first cell as table header/identifier
Dim tableIdentifier As String = table.Rows(0).Cells(0).ExtractText()
extractedContent.AppendLine(vbCrLf & $"TABLE: {tableIdentifier}")
' Extract key metrics (last row often contains totals)
If table.Rows.Count > 1 Then
Dim lastRow = table.Rows.Last()
Dim totals = lastRow.Cells.Select(Function(cell) cell.ExtractText())
extractedContent.AppendLine($"Totals: {String.Join(", ", totals)}")
End If
Next
' 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() 访问特定单元格,即可检索文档中任何表格单元格的文本内容。
使用 ExtractText() 时,提取的文本按照什么顺序排列?
IronWord 的 ExtractText() 方法可以保持文档的逻辑阅读顺序,依次处理标题、段落、列表和其他文本元素,是内容分析和搜索索引的理想选择。
开始从 DOCX 文件中提取文本的基本步骤是什么?
首先通过 NuGet 安装 IronWord(Install-Package IronWord),然后创建或加载 WordDocument,最后使用 ExtractText() 方法根据需要从整个文档、特定段落或表格单元格中获取文本。
文本提取是否适合构建文档索引系统?
是的,IronWord 的文本提取功能非常适合构建文档索引系统、内容管理解决方案和数据提取管道,提供对 Word 文档内容的高效编程访问。

