public string ReadWord(string fileName, int rowIndex, int colIndex)
{
ApplicationClass cls = new ApplicationClass();
Document doc = null; Table table = null; object missing = Missing.Value;
object path = fileName;
try
{
doc = cls.Documents.Open(ref path, ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
table = doc.Tables[1];
string text = table.Cell(rowIndex, colIndex).Range.Text;
return text.Substring(0, text.Length - 2);
}
catch (Exception ex) { return ex.Message; }
finally
{
doc?.Close(ref missing, ref missing, ref missing);
cls?.Quit(ref missing, ref missing, ref missing);
}
}
參考 ADO.NET SqlConnection/SqlCommand 模式,分離 Open、ReadWord、Close,避免重複啟動 Word 進程。
Open():建立 ApplicationClass、開啟文件。ReadWord(tableIndex, rowIndex, colIndex):讀取指定表格儲存格。Close():關閉文件與 Word 應用程式。類別結構圖(略)顯示欄位、屬性與方法關係。