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

使用 C# 讀取 Word 表格資料(二):封裝類別與效能優化

     編輯:關於C語言

WordTableRead 類別

class WordTableRead
{
    string fileName; ApplicationClass cls; Document doc; Table table; object missing = Missing.Value; bool openState;

    public WordTableRead(string fileName) { this.fileName = fileName; }

    public void Open()
    {
        object path = fileName;
        cls = new ApplicationClass();
        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);
            openState = true;
        }
        catch { openState = false; }
    }

    public string ReadWord(int tableIndex, int rowIndex, int colIndex)
    {
        try
        {
            if (!openState) return "";
            table = doc.Tables[tableIndex];
            string text = table.Cell(rowIndex, colIndex).Range.Text;
            return text.Substring(0, text.Length - 2); // 移除結尾控制字元
        }
        catch { return "Error"; }
    }

    public void Close()
    {
        if (openState)
        {
            doc?.Close(ref missing, ref missing, ref missing);
            cls?.Quit(ref missing, ref missing, ref missing);
        }
    }
}

已知問題與優化方向

  • 讀取速度不滿意,特別是大量儲存格時。
  • 主控台應用程式無法直接看到輸出,需加入日誌或事件回呼。
  • 建議:重複讀取同一文件時保持開啟(本類別已支援);考慮改用 Open XML SDK 操作 .docx 免安裝 Word、效能更佳;或使用 Microsoft.Office.Interop.Word 的 Range 批次讀取整個表格再解析。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved