在日常辦公和開發中,我們經常需要從 Word 文檔中提取表格數據進行二次處理(如導入數據庫、數據分析等)。本文將介紹如何使用 C# 結合 Spire.Doc 庫實現 Word 表格的提取,並將提取的內容保存為文本文件。
工具與環境準備
要實現Word表格提取,我們需要以下工具和組件:
- 開發環境:Visual Studio(或其他 C# 開發工具)
- .NET Framework/.NET Core(本文代碼兼容主流版本)
- 第三方庫:Spire.Doc(用於解析 Word 文檔結構,處理表格數據)
Spire.Doc 是一個功能強大的Word文檔處理庫,支持讀取、編輯、生成Word文檔,尤其對錶格、段落等元素的處理非常便捷。我們可以通過 NuGet 包管理器安裝它:在項目中右鍵“管理NuGet包”,搜索“Spire.Doc”並安裝。
如何通過 C# 提取 Word 表格
實現思路
從Word中提取表格的核心思路是“逐層解析文檔結構”:
- 加載Word文檔,獲取文檔對象
- 遍歷文檔中的“節(Section)”(Word文檔的基本結構單位)
- 在每個節中獲取表格集合,遍歷所有表格
- 對每個表格,逐行、逐單元格提取文本內容
- 將提取的表格數據按格式保存到文本文件
完整代碼
以下是提取Word表格的完整代碼,我們將逐步解析其核心邏輯:
using Spire.Doc;
using Spire.Doc.Collections;
using Spire.Doc.Interface;
using System.IO;
using System.Text;
namespace ExtractWordTable
{
internal class Program
{
static void Main(string[] args)
{
// 創建文檔對象
Document doc = new Document();
// 加載Word文檔
doc.LoadFromFile("Tables.docx");
// 遍歷文檔中的所有節
for (int sectionIndex = 0; sectionIndex < doc.Sections.Count; sectionIndex++)
{
Section section = doc.Sections[sectionIndex];
// 獲取當前節中的所有表格
TableCollection tables = section.Tables;
// 遍歷當前節中的所有表格
for (int tableIndex = 0; tableIndex < tables.Count; tableIndex++)
{
ITable table = tables[tableIndex];
// 用於存儲當前表格的所有數據
string tableData = "";
// 遍歷表格中的所有行
for (int rowIndex = 0; rowIndex < table.Rows.Count; rowIndex++)
{
TableRow row = table.Rows[rowIndex];
// 遍歷行中的所有單元格
for (int cellIndex = 0; cellIndex < row.Cells.Count; cellIndex++)
{
TableCell cell = row.Cells[cellIndex];
// 提取單元格文本(單元格可能包含多個段落)
string cellText = "";
for (int paraIndex = 0; paraIndex < cell.Paragraphs.Count; paraIndex++)
{
cellText += (cell.Paragraphs[paraIndex].Text.Trim() + " ");
}
// 拼接單元格文本,用製表符分隔不同單元格
tableData += cellText.Trim();
if (cellIndex < row.Cells.Count - 1)
{
tableData += "\t";
}
}
// 行結束後換行
tableData += "\n";
}
// 保存表格數據到文本文件)
string filePath = Path.Combine("Tables", $"Section{sectionIndex + 1}_Table{tableIndex + 1}.txt");
File.WriteAllText(filePath, tableData, Encoding.UTF8);
}
}
doc.Close();
}
}
}
代碼核心邏輯解析
1. 遍歷文檔結構
Word 文檔的結構是“文檔(Document)→ 節(Section)→ 表格(Table)→ 行(Row)→ 單元格(Cell)”,因此我們需要逐層遍歷:
- 節(Section):一個Word文檔可以包含多個節(如不同的頁面設置、分欄等),通過
doc.Sections獲取所有節。 - 表格(Table):每個節中可能包含多個表格,通過
section.Tables獲取當前節的表格集合。
2. 提取單元格文本
單元格(TableCell)中的內容可能包含多個段落(Paragraph),因此需要遍歷所有段落並拼接文本:
string cellText = "";
for (int paraIndex = 0; paraIndex < cell.Paragraphs.Count; paraIndex++)
{
cellText += (cell.Paragraphs[paraIndex].Text.Trim() + " ");
}
使用Trim()去除文本前後的空白,避免多餘空格影響格式。
實用擴展方向
基於本文代碼,可進一步擴展功能,滿足更多場景需求:
- 將提取的表格數據導出為 Excel 文件(結合 Spire.XLS 庫)
- 對提取的文本進行清洗(如去除特殊符號、格式轉換)
- 批量處理多個Word文檔(遍歷文件夾中的所有.docx文件)
通過上述方法,我們可以高效地從 Word 文檔中提取表格數據,為後續的數據處理提供便利。相比原生 Office Interop,Spire.Doc 無需依賴 Office 客户端,運行更輕量化;代碼邏輯清晰,可直接複用或二次開發。