使用IronWord从DOCX中提取文本
IronWord 的 ExtractText() 方法可从 DOCX 文件的整个文档、指定段落或表格单元格中提取文本,为 C# 文档处理和数据分析任务提供易用的 API。
-
1使用 IronWord 安装 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);Imports IronWord ' Quick example: Extract all text from DOCX Dim doc As New WordDocument("sample.docx") Dim allText As String = doc.ExtractText() Console.WriteLine(allText)Imports IronWord ' Quick example: Extract all text from DOCX Dim doc As New WordDocument("sample.docx") Dim allText As String = doc.ExtractText() Console.WriteLine(allText) -
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());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())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);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)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统计表的文档,并从第3行的第4列提取一个特定单元格值。
表格提取对于数据迁移项目、报告生成和自动数据收集工作流至关重要。 处理表格数据时,了解从零开始的索引系统至关重要——第一个表是Tables[0],第一行是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}");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}");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 3rd row
Dim extractedValue As String = DirectCast(apiStatsDoc.Tables(0).Rows(2).Cells(3), TableCell).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 3rd row
Dim extractedValue As String = DirectCast(apiStatsDoc.Tables(0).Rows(2).Cells(3), TableCell).ExtractText()
' Print extracted value
Console.WriteLine($"Target success rate: {extractedValue}")示例代码通过集合属性 Tables、Rows 和 Cells 访问表格单元格。Cells 集合返回实现 ITableCell 接口的对象,需要将其强制转换为 TableCell,才能调用 ExtractText 方法:((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());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());Imports IronWord
Imports IronWord.Models
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 = DirectCast(table.Rows(0).Cells(0), TableCell).ExtractText()
extractedContent.AppendLine(vbLf & $"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) DirectCast(cell, TableCell).ExtractText())
extractedContent.AppendLine($"Totals: {String.Join(", ", totals)}")
End If
Next
' Save the structured extraction
System.IO.File.WriteAllText("structured-extract.txt", extractedContent.ToString())Imports IronWord
Imports IronWord.Models
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 = DirectCast(table.Rows(0).Cells(0), TableCell).ExtractText()
extractedContent.AppendLine(vbLf & $"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) DirectCast(cell, TableCell).ExtractText())
extractedContent.AppendLine($"Totals: {String.Join(", ", totals)}")
End If
Next
' Save the structured extraction
System.IO.File.WriteAllText("structured-extract.txt", extractedContent.ToString())此示例演示如何结合不同的文档元素,获得结构化的提取结果。这种方法可用于生成文档摘要、创建索引或准备待处理的数据。正如升级可扩展软件功能,结合多种提取方法也可以扩展文档处理能力。
文本提取的最佳实践
在生产应用程序中实施文本提取时,请考虑以下最佳实践:
- 错误处理:始终将提取代码包装在try-catch块中,以处理可能损坏或具有意外结构的文档。
- 性能优化:对于大型文档或批处理操作,请考虑仅提取必要的部分,而不是整个文档内容。
- 字符编码:保存提取文本时请注意字符编码,尤其是对于包含特殊字符或多语言的文档。
- 内存管理:处理多个文档时,应正确释放
WordDocument对象以防止内存泄漏。
请记住,文本提取会保留逻辑阅读顺序,但会删除格式。 如果您需要保持格式信息,请考虑使用其他IronWord功能或单独存储元数据。 对于生产部署,请查看变更日志以随时了解最新功能和改进。
总结
IronWord的ExtractText()方法提供了一种强大且灵活的方式从DOCX文件中提取文本。 无论您需要提取整个文档、特定段落还是表格数据,API 都能提供直接的方法来实现您的目标。 通过将这些技术与正确的错误处理和优化策略结合,您可以构建可靠的文档处理应用程序,能够高效处理各种文本提取场景。
对于更高级的场景和探索其他功能,请查看扩展和其他文档资源,以增强您的文档处理能力。
常见问题
如何使用IronWord从DOCX文档中提取所有文本?
可以使用IronWord的ExtractText()方法提取DOCX文档中的所有文本。该方法通过顺序处理标题、段落、列表和其他元素,从而维护逻辑阅读顺序。它对内容分析和搜索索引应用程序非常有用。
我可以从DOCX文件中的特定段落提取文本吗?
是的,IronWord允许您通过访问Paragraphs集合从特定段落提取文本。此方法为处理的部分提供了控制,使其适合具有结构化内容的文档,或者需要独立处理特定部分的情况。
IronWord如何处理从DOCX文件的表格单元格中提取文本?
IronWord通过导航Tables、Rows和Cells集合来实现从表格单元格的提取。通过使用从零开始的索引,您可以访问特定单元格,从而在结构化文档中实现高效的数据迁移、报表生成或采集工作流程。
使用IronWord的高级文本提取场景有哪些?
高级场景包括提取标题、表格摘要以及从多个元素组合提取内容。这种方法适用于生成文档摘要或索引,涉及使用ExtractText()和特定文档元素方法的组合。
使用IronWord进行文本提取时应遵循哪些最佳实践?
实施IronWord的文本提取涉及使用try-catch块处理错误,通过定位必要内容来优化性能,管理字符编码,并确保适当的内存管理以防止多个文档处理期间的泄漏。
IronWord如何在提取期间维护文本顺序?
IronWord通过顺序处理文本元素(如标题、段落和列表)来维护逻辑阅读顺序。此提取结构对于需要内容分析和索引的应用程序特别有价值。
如何使用IronWord将提取的文本导出到文件?
一旦提取了文本,您可以使用C#文件处理方法,如File.WriteAllText,将文本保存到文件中,正如教程中使用段落提取演示的那样,组合文本被保存到output.txt文件。
是否可以单独提取引言和结论部分?
是的,可以通过在Paragraphs集合中定位来提取特定段落,如引言和结论。这种方法对于需要对关键部分进行独特提取的文档摘要工具很有效。
保存提取的文本时应注意哪些编码问题?
IronWord用户在处理包含特殊字符或多语言的文档时应注意字符编码。确保正确编码对于在保存提取的文本时维护文本完整性至关重要。
如何优化IronWord的文本提取以处理大型文档?
针对大型文档,优化文本提取可通过只定位必要部分而不是提取整个内容来实现。这确保了效率,减少了处理时间,并充分利用了IronWord的全部功能。
Ahmad 是一名全栈开发人员,拥有扎实的 C#、Python 和 Web 技术基础。他对构建可扩展的软件解决方案深感兴趣,并喜欢探索设计和功能在实际应用中如何结合。