使用 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 欄的儲存格值。
擷取表格資料是資料移轉、報表產生及自動化資料收集的重要步驟。表格索引從 0 開始,第一個表格是 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 技術。他對建立可擴展的軟體解決方案有著濃厚的興趣,並樂於探索如何在實際應用中實現設計與功能的完美結合。