萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 辦公室軟體 >  >> Word 教學 >> Word 使用技巧

C# 透過 COM 互操作讀取 Word 文件屬性:作者與主題

程式碼範例:自動化擷取 Word 內建文件屬性

using Word = Microsoft.Office.Interop.Word;
using System.Reflection;
using System.Runtime.InteropServices;

// ... 參考 Microsoft.Office.Interop.Word ...

Word.Application oWord = new Word.Application();
Word._Document oDoc = null;
object oMissing = Missing.Value;
object source = @"DocPath";
object unknown = Type.Missing;

try {
    oDoc = oWord.Documents.Open(ref source, ref unknown, ref unknown, ref unknown,
        ref unknown, ref unknown, ref unknown, ref unknown,
        ref unknown, ref unknown, ref unknown, ref unknown);

    object docBuiltInProps = oDoc.BuiltInDocumentProperties;
    Type typeProps = docBuiltInProps.GetType();

    // 取得作者
    string index = "Author";
    object docAuthor = typeProps.InvokeMember("Item", BindingFlags.Default | BindingFlags.GetProperty,
        null, docBuiltInProps, new object[] { index });
    Type typeAuthor = docAuthor.GetType();
    string author = typeAuthor.InvokeMember("Value", BindingFlags.Default | BindingFlags.GetProperty,
        null, docAuthor, new object[] {} ).ToString();
    MessageBox.Show(author, "Author");

    // 取得主題
    index = "Subject";
    object docSubject = typeProps.InvokeMember("Item", BindingFlags.Default | BindingFlags.GetProperty,
        null, docBuiltInProps, new object[] { index });
    Type typeSubject = docSubject.GetType();
    string subject = typeSubject.InvokeMember("Value", BindingFlags.Default | BindingFlags.GetProperty,
        null, docSubject, new object[] {} ).ToString();
    MessageBox.Show(subject, "Subject");
}
finally {
    object save = false;
    oWord.Quit(ref save, ref unknown, ref unknown);
    Marshal.ReleaseComObject(oWord);
}

關鍵點解析

  • 使用晚期繫結 InvokeMember 避免版本相依,支援 Word 2003 到最新版。
  • BuiltInDocumentProperties 包含:Title, Subject, Author, Keywords, Comments, Template, LastAuthor, RevisionNumber, ApplicationName, LastPrintDate, CreationDate, LastSaveTime, TotalEditingTime, Pages, Words, Characters, Security, Category, Format, Manager, Company, Bytes, Lines, Paragraphs, Slides, Notes, HiddenSlides, MMClips 等。
  • 釋放 COM 物件順序:先 Quit 再 ReleaseComObject,防止 Word 進程殭屍。
  • 生產環境建議加入錯誤處理、日誌、超時機制;大量檔案處理考慮使用 Open XML SDK (無需安裝 Word) 或 LibreOffice headless 模式。
copyright © 萬盛學電腦網 all rights reserved