需從現有 Word 文件(.doc/.docx)提取表格資料匯入資料庫或進一步處理時,官方提供的 Microsoft.Office.Interop.Word (PIA) 是最直接的方案。本文示範開啟文件、遍歷所有表格、逐列逐欄讀取儲存格文字、處理換行符號的完整流程。
Microsoft.Office.Interop.Word(Visual Studio 安裝 Office 開發工具時自動註冊 PIA)。using Word = Microsoft.Office.Interop.Word;
object fileName = @"C:\Docs\TestDoc.doc";
object readOnly = true;
object missing = Missing.Value;
Word.Application wordApp = new Word.Application();
wordApp.Visible = true; // 僅為除錯觀察,正式環境設 false
Word.Document 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 t = 1; t <= doc.Tables.Count; t++)
{
Word.Table table = doc.Tables.Item(t);
string msg = $"第 {t}/{doc.Tables.Count} 個表:\n";
for (int r = 1; r <= table.Rows.Count; r++)
{
for (int c = 1; c <= table.Columns.Count; c++)
{
string cellText = table.Cell(r, c).Range.Text;
// Word 儲存格文字結尾帶有 \r\a (ASCII 13, 7),需移除
if (cellText.Length >= 2) cellText = cellText.Substring(0, cellText.Length - 2);
msg += cellText + "\t";
}
msg += "\n";
}
MessageBox.Show(msg); // 實務上改為存入 List/DataTable/資料庫
}
// 釋放資源
doc.Close(false, missing, missing);
wordApp.Quit();
Marshal.ReleaseComObject(doc);
Marshal.ReleaseComObject(wordApp);
\r\a (Carriage Return + Cell Delimiter),必須 TrimEnd('\r', '\a') 或 Substring 移除。Cell(r,c) 若屬於合併區域,會拋出例外;需先判斷 table.Cell(r,c).Range.Information[Word.WdInformation.wdWithInTable] 或捕捉例外跳過。table.Range.Text 再自行解析,或改用 Open XML SDK / NPOI / DocX 純 .NET 解析,不需安裝 Word。文章附上 VB.NET 版本,展示其 WithEvents、選擇性參數省略、Nothing 等語法優勢,COM 互操作確實比 C# 簡潔許多。
掌握 Word Interop 表格讀取,能快速完成文件資料數位化,但請務必評估部署環境是否適合 COM 方案。