Word 文件 (.doc/.docx) 為二進位/壓縮 XML 格式,直接解析極其困難。標準做法:使用 Microsoft Word PIA (Primary Interop Assembly) 透過 COM 自動化操作 Word 應用程式,提取表格資料。本文完整示範開啟文件、遍歷表格/列/欄、提取儲存格文字的代碼,並對比 VB.NET 簡潔性。
object fileName = @"C:\Docs\TestDoc.doc";
object readOnly = true;
object missing = Type.Missing;
var wordApp = new Microsoft.Office.Interop.Word.Application();
wordApp.Visible = true; // 僅為除錯觀察
var doc = wordApp.Documents.Open(
ref fileName, ref missing, ref readOnly, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing);
for (int tableIdx = 1; tableIdx <= doc.Tables.Count; tableIdx++)
{
var table = doc.Tables[tableIdx];
var msg = $"第 {tableIdx}/{doc.Tables.Count} 個表:\n";
for (int rowIdx = 1; rowIdx <= table.Rows.Count; rowIdx++)
{
for (int colIdx = 1; colIdx <= table.Columns.Count; colIdx++)
{
var cellText = table.Cell(rowIdx, colIdx).Range.Text;
// 移除結尾 \r\a (儲存格標記)
if (cellText.Length >= 2) cellText = cellText.Substring(0, cellText.Length - 2);
msg += cellText + "\t";
}
msg += "\n";
}
MessageBox.Show(msg);
}
// 清理 COM 物件 (重要!)
Marshal.ReleaseComObject(doc);
wordApp.Quit(ref missing, ref missing, ref missing);
Marshal.ReleaseComObject(wordApp);
| 點 | 說明 |
|---|---|
| 索引從 1 開始 | Word 物件模型集合 (Tables、Rows、Columns、Cells) 皆為 1-based |
| 儲存格文字結尾 | Range.Text 以 "\r\a" (CR + 儲存格標記) 結尾,需移除 |
| COM 物件釋放 | 必須呼叫 Marshal.ReleaseComObject,否則 Word 進程殘留 |
| 選用參數 | C# 需傳 ref missing (Type.Missing),VB.NET 可省略 |
| 可見性 | 生產環境設 Visible = false,避免 UI 干擾 |
Dim fileName = "C:\Docs\TestDoc.doc"
Dim wordApp = New Word.Application()
Dim wordDoc = wordApp.Documents.Open(fileName, , True) ' 選用參數省略
wordApp.Visible = True
For Each table As Word.Table In wordDoc.Tables
' 直接 For Each 遍歷,無需索引
Dim msg = ""
For Each row As Word.Row In table.Rows
For Each cell As Word.Cell In row.Cells
msg += cell.Range.Text.Replace(vbCr & "a", "") & vbTab
Next
msg += vbCrLf
Next
MessageBox.Show(msg)
Next
VB.NET 優勢:選用參數省略、For Each 直接遍歷 COM 集合、字串處理內建函數。
| 方案 | 適用格式 | 優點 | 缺點 |
|---|---|---|---|
| Open XML SDK | .docx | 無需 Office、高效能、純 managed | 不支援 .doc、API 複雜 |
| NPOI | .doc/.docx | Java 移植、支援舊格式 | 效能較差、記憶體佔用大 |
| DocX (NuGet) | .docx | API 簡潔、無依賴 | 功能有限 |
| LibreOffice + UNO | .doc/.docx | 跨平台、免費 | 需安裝 LibreOffice、啟動慢 |