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

C# 讀取 Word 表格資料:COM Interop 封裝與效能優化

     編輯:關於C#

基礎讀取方法

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);
    }
}

問題:頻繁開關 Word 進程極慢

每次呼叫都啟動 WINWORD.EXE,讀百個儲存格需數分鐘。

優化:封裝類別複用單一 Word 實例


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));
}

進階優化方向

  • Open XML SDK (DocumentFormat.OpenXml):無需安裝 Office、純 managed code、效能極佳、支援 .docx 解析 XML 結構直接讀取表格。
  • NPOI:支援 .doc/.xls/.xlsx,Java POI 移植版。
  • 非同步批次:將讀取佇列交給背景執行緒,UI 不阻塞。

Open XML SDK 範例

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 依賴、速度快數十倍、部署輕量。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved