需從 Word 文件(`.doc`)指定表格的指定儲存格讀取文字。網路資料良莠不齊:碼農複製貼上、缺自訂類別實作、無架構說明。經數週篩選整理,形成可落地方案。
| Id | Name |
|---|---|
| 1 | Wulei |
| 2 | Jack |
using Word = Microsoft.Office.Interop.Word;
public string GetCellText(string filePath, int tableIndex, int row, int col)
{
Word.Application app = null;
Word.Document doc = null;
try
{
app = new Word.Application { Visible = false };
doc = app.Documents.Open(filePath, ReadOnly: true);
if (doc.Tables.Count < tableIndex) return null;
var table = doc.Tables[tableIndex];
if (table.Rows.Count < row || table.Columns.Count < col) return null;
return table.Cell(row, col).Range.Text.Trim('\r', '\a'); // 移除儲存格結束符
}
finally
{
doc?.Close(false);
app?.Quit(false);
}
}
WinForms 介面:`TextBox` 顯示檔案路徑、`Button` 觸發 `OpenFileDialog`、第二個 `Button` 讀取第 2 列第 1 欄 → 顯示於另一 `TextBox`。截圖見原文。