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

C# 讀取 Word 文件內容:使用 Microsoft Word COM 互操作

     編輯:關於C#

由於 Word 檔案為二進位/複合格式,無法直接用 FileStream 讀取純文字。最常見做法是透過 Microsoft.Office.Interop.Word COM 元件自動化 Word 應用程式開啟文件、全選、複製到剪貼簿、再取出純文字。

必要參考

  • 專案 → 加入參考 → COM → Microsoft Word 14.0/15.0/16.0 Object Library
  • using Word = Microsoft.Office.Interop.Word;

核心程式碼


using Word = Microsoft.Office.Interop.Word;
using System.Windows.Forms; // Clipboard, DataFormats

public string ReadWordText(string filePath)
{
    Word.Application app = null;
    Word.Document doc = null;
    try
    {
        app = new Word.Application { Visible = false };
        object file = filePath;
        object missing = Type.Missing;

        doc = app.Documents.Open(ref file, 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);

        doc.ActiveWindow.Selection.WholeStory();
        doc.ActiveWindow.Selection.Copy();

        IDataObject data = Clipboard.GetDataObject();
        if (data.GetDataPresent(DataFormats.Text))
            return data.GetData(DataFormats.Text).ToString();
        return string.Empty;
    }
    finally
    {
        if (doc != null)
        {
            object saveChanges = Word.WdSaveOptions.wdDoNotSaveChanges;
            doc.Close(ref saveChanges);
        }
        if (app != null)
            app.Quit();
        // 釋放 COM 物件
        if (doc != null) System.Runtime.InteropServices.Marshal.ReleaseComObject(doc);
        if (app != null) System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
        GC.Collect(); GC.WaitForPendingFinalizers();
    }
}

重要注意事項

  • Office 必須安裝在執行機器:此法需完整 Word 應用程式,不適用於無 Office 的伺服器環境。
  • 效能與資源:啟動 Word 進程較重,批次處理大量檔案會極慢且易導致記憶體洩漏,務必正確釋放 COM 物件。
  • 安全性:Word 可能彈出對話框(如轉換器確認、巨集警告),需設定 AutomationSecurity 或使用無訊息模式。
  • 替代方案:
    • Open XML SDK:解析 .docx (OOXML) 結構,不需 Office,效能佳,適合伺服器端。
    • NPOI / DocX:開源庫支援 .doc/.docx 讀寫。
    • 第三方商業元件:Aspose.Words、GemBox.Document 功能完整。

適用場景

桌面應用程式、低頻率讀取、需完整排版還原時使用 COM 互操作;伺服器端、高效能、批次處理請改用 Open XML SDK 或 NPOI。

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