public string ReadCell(string filePath, int row, int col)
{
Application app = new Application();
Document doc = null;
try
{
object missing = Missing.Value;
object path = filePath;
doc = app.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 table = doc.Tables[1]; // 取第一個表格
string text = table.Cell(row, col).Range.Text;
return text.Substring(0, text.Length - 2); // 移除結尾控制字元
}
finally
{
doc?.Close(ref missing, ref missing, ref missing);
app.Quit(ref missing, ref missing, ref missing);
}
}
每次呼叫都啟動 WINWORD.EXE,讀百個儲存格需數分鐘。
public class WordTableReader : IDisposable
{
private readonly string _path;
private Application _app;
private Document _doc;
private bool _opened;
public WordTableReader(string path) { _path = path; }
public void Open()
{
if (_opened) return;
_app = new Application();
object missing = Missing.Value, path = _path;
_doc = _app.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);
_opened = true;
}
public string ReadCell(int tableIndex, int row, int col)
{
if (!_opened) throw new InvalidOperationException("請先呼叫 Open()");
Table table = _doc.Tables[tableIndex];
string text = table.Cell(row, col).Range.Text;
return text.Substring(0, text.Length - 2);
}
public void Dispose()
{
if (!_opened) return;
object missing = Missing.Value, save = false;
_doc?.Close(ref save, ref missing, ref missing);
_app?.Quit(ref missing, ref missing, ref missing);
_opened = false;
}
}
// 使用
using (var reader = new WordTableReader(@"C:\data.docx"))
{
reader.Open();
for (int r = 1; r <= 100; r++)
Console.WriteLine(reader.ReadCell(1, r, 1));
}
DocumentFormat.OpenXml):無需安裝 Office、純 managed code、效能極佳、支援 .docx 解析 XML 結構直接讀取表格。using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
public IEnumerable ReadTableOpenXml(string path, int tableIndex)
{
using (WordprocessingDocument doc = WordprocessingDocument.Open(path, false))
{
var tables = doc.MainDocumentPart.Document.Body.Elements();
Table table = tables.ElementAt(tableIndex - 1);
foreach (TableRow row in table.Elements())
{
yield return row.Elements()
.Select(c => c.InnerText).ToArray();
}
}
}
小結
COM Interop 相容性好但效能差、需安裝 Office。**生產環境強烈建議改用 Open XML SDK**,無 Office 依賴、速度快數十倍、部署輕量。
- 上一篇文章: C# BitmapData 直接操作像素:unsafe 指針高效影像處理實戰
- 下一篇文章: C# 透過 ODBC 操作 DBF (FoxPro/Visual FoxPro) 資料庫完整指南
Copyright © 程式碼之家 All Rights Reserved