使用 IronWord 從 DOCX 檔案中擷取文字

This article was translated from English: Does it need improvement?
Translated
View the article in English

IronWord 的 ExtractText() 方法可讓您透過存取整個文件、特定段落或表格儲存格,從 DOCX 檔案中擷取文字,為 C# 中的文件處理與資料分析任務提供簡易的 API。

快速入門:從 DOCX 檔案中擷取文字

  1. using NuGet 套件管理員安裝 https://www.nuget.org/packages/IronWord

    PM > Install-Package IronWord
  2. 請複製並執行此程式碼片段。

    using IronWord;
    
    // Quick example: Extract all text from DOCX
    WordDocument doc = new WordDocument("sample.docx");
    string allText = doc.ExtractText();
    Console.WriteLine(allText);
  3. 部署至您的生產環境進行測試

    立即透過免費試用,在您的專案中開始使用 IronWord

    arrow pointer

如何從 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())
$vbLabelText   $csharpLabel

提取的文字內容為何?

顯示

我在控制台應看到什麼輸出?

程式碼範例展示 Console.WriteLine 輸出擷取的文字,並透過除錯主控台顯示

如何從特定段落中擷取文字?

若需更精細的控制,您可以從特定段落中擷取文字,而非整個文件。 透過存取 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)
$vbLabelText   $csharpLabel

當結合文件分析需求時,提取特定段落的能力將變得極為強大。 例如,您可以根據段落的格式、位置或內容模式來擷取關鍵段落。 這種選擇性擷取的方法有助於縮短處理時間,並聚焦於最相關的內容。

從第一段中提取了哪些內容?

展示文字擷取示範的 WORD 文件,其中紅色格式段落位於黑色文字段落上方

從最後一段中提取了哪些內容?

Microsoft WORD 文件,顯示格式化的段落,其中紫色與藍色的文字為 Lorem ipsum 範例文字

合併後的文字在輸出檔案中會呈現為何種樣式?

文字編輯器顯示段落提取點,以紅藍箭頭標示段落邊界

上方的螢幕截圖分別顯示了第一段落擷取、最後一段落擷取,以及儲存至文字檔案的合併輸出結果。請注意,擷取過程在移除格式資訊的同時保留了文字內容,使其適合用於純文字處理。

如何從 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}")
$vbLabelText   $csharpLabel

此程式碼示範如何使用集合屬性 RowsCells 存取表格儲存格。 請注意,Cells 集合會傳回 ITableCell 介面物件,必須將其強制轉換為 TableCell 才能存取 ExtractText 方法:((TableCell)cell).ExtractText()。 這需要在您的命名空間宣告中加入 using IronWord.Models;

原始表格的樣式為何?

WORD 文件中的 API 使用統計表,顯示 6 個端點的請求次數、延遲、成功率及頻寬指標

從表格儲存格中擷取了什麼值?

Visual Studio 除錯主控台顯示的擷取表格值

進階文字擷取情境

在處理複雜文件時,您可能需要結合多種擷取技術。 以下範例展示如何從多個元素中擷取文字,並對其進行不同處理:

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())
$vbLabelText   $csharpLabel

此進階範例展示如何透過組合不同的文件元素來建立結構化擷取內容。 此方法適用於生成文件摘要、建立索引,或為後續處理預先準備資料。 正如升級能提升軟體功能,結合多種擷取方法也能強化您的文件處理能力。

文字擷取的最佳實務

在生產環境的應用程式中實作文字擷取時,請參考以下最佳實務:

  1. 錯誤處理:請務必將資料擷取程式碼包覆於 try-catch 區塊中,以處理可能已損毀或具有意外結構的文件。

  2. 效能優化:針對大型文件或批次處理,建議僅擷取必要部分,而非整個文件內容。

  3. 字元編碼:儲存擷取的文字時,請注意字元編碼,特別是對於包含特殊字元或多種語言的文件。

  4. 記憶體管理:處理多個文件時,請妥善釋放 WordDocument 物件,以防止記憶體洩漏。

請注意,文字擷取會保留邏輯閱讀順序,但會移除格式設定。 若需保留格式資訊,請考慮使用額外的 IronWord 功能,或將元資料另行儲存。 若進行生產環境部署,請查閱變更日誌以掌握最新功能與改進內容。

摘要

IronWord 的 ExtractText() 方法提供了一種強大且靈活的方式,用於從 DOCX 檔案中擷取文字。 無論您需要擷取整份文件、特定段落或表格資料,此 API 皆提供簡便的方法來達成您的目標。 透過將這些技術與適當的錯誤處理及優化策略結合,您將能建置穩健的文件處理應用程式,以高效處理各種文字擷取情境。

若需處理更複雜的場景或探索更多功能,請參閱擴充功能及其他文件資源,以提升您的文件處理能力。

常見問題

如何使用 C# 從 WORD 文件中擷取所有文字?

請在 WordDocument 物件上使用 IronWord 的 ExtractText() 方法。只需透過 WordDocument doc = new WordDocument("document.docx"); 載入您的 DOCX 檔案,然後呼叫 string text = doc.ExtractText(); 即可從文件中擷取所有文字內容。

我可以從特定段落中擷取文字,而非整個文件嗎?

是的,IronWord 允許您透過存取 Paragraphs 集合,從特定段落中擷取文字。請使用 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 文件內容存取方式。

Ahmad Sohail
全端開發者

Ahmad 是一位全端開發者,具備扎實的 C#、Python 及網頁技術基礎。他對建構可擴展的軟體解決方案深感興趣,並樂於探索設計與功能如何在實際應用中完美結合。

在加入 Iron Software 團隊之前,Ahmad 曾參與自動化專案與 API 整合工作,專注於提升效能與開發者體驗。

閒暇之餘,他喜歡嘗試 UI/UX 創意、為開源工具貢獻心力,並偶爾投入技術寫作與文件編寫,致力於將複雜的主題轉化為淺顯易懂的內容。

準備開始了嗎?
Nuget 下載 44,829 | 版本: 2026.5 just released
Still Scrolling Icon

還在往下捲動嗎?

想要快速確認成果嗎? PM > Install-Package IronWord
執行範例 觀看您的資料轉為 WORD 文件。