首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 讀取 Word 表格資訊完整實現:COM Interop 操作 Word 文件提取表格資料

     編輯:關於C語言

前言

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 干擾

VB.NET 版本對比 (極度簡潔)

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 集合、字串處理內建函數。

官方文件與資源

現代替代方案 (無需安裝 Word)

總結

Word COM Interop 是提取 .doc 表格資料的唯一官方方案,但部署需安裝 Word、權限複雜、效能差。現代專案請優先要求使用者提供 .docx,改用 Open XML SDK 或 DocX 純 managed 解析。若必須處理 .doc,建議架設轉換服務 (LibreOffice headless) 先轉 .docx 再解析,避免生產環境直接自動化 Word。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
方案適用格式優點缺點
Open XML SDK.docx無需 Office、高效能、純 managed不支援 .doc、API 複雜
NPOI.doc/.docxJava 移植、支援舊格式效能較差、記憶體佔用大
DocX (NuGet).docxAPI 簡潔、無依賴功能有限
LibreOffice + UNO.doc/.docx跨平台、免費需安裝 LibreOffice、啟動慢