Coding With Office Word


  1. 說明
    1. Coding

筆記使用 Microsoft.Office.Interop 以 C# 來開發設計 Word 文件應用。

Microsoft Word

說明

首先需要加入參考,在專案中選擇加入參考後選擇「COM」,如果要編輯的是 Word 文件則加入 Microsoft Word 16.0 Object Library,如果是 Excel 則加入 Microsoft Excel 16.0 Object Library

負責執行 C# 的作業系統必需要安裝 Office 才能夠正常運作,本次的示範安裝的是 Microsoft 365 Apps 版本 2301。

Coding

執行前後的對照

static void Main(string[] args)
{
    string path = @"C:\temp\Hello.doc";

    Application wordApp = new Application
    {
        Visible = false // 讓 Word 在背景執行
    };

    var wordDoc = wordApp.Documents.Open(path);

    // 讀取 Word 所有文字段落
    foreach (Paragraph p in wordDoc.Paragraphs)
    {
        Console.WriteLine(p.Range.Text);
    }

    // 尋找符合的內容並進行取代
    wordDoc.Content.Find.Execute(
        FindText: "Hello World", ReplaceWith: "C# Love Office");

    // 迭代所有段落,尋找符合的關鍵字後取代內容與調整段落文字顏色
    foreach (Paragraph paragraph in wordDoc.Paragraphs)
    {
        if (paragraph.Range.Text.Contains("JavaScript"))
        {
            var range = paragraph.Range;
            range.Find.Execute(FindText: "JavaScript", ReplaceWith: "JS", Replace: WdReplace.wdReplaceAll);

            range.Font.Color = WdColor.wdColorRed;
        }
    }

    // 迭代所有的表格內容
    var table = wordDoc.Tables[1];
    for (int row = 1; row <= table.Rows.Count; row++)
    {
        for (int col = 1; col <= table.Columns.Count; col++)
        {
            Console.WriteLine(table.Cell(row, col).Range.Text);
        }
    }

    // 新增表格資料列
    table.Rows.Add();
    var newRow = table.Rows[table.Rows.Count];
    newRow.Cells[1].Range.Text = "傑尼龜";
    newRow.Cells[2].Range.Text = "8";
    newRow.Cells[3].Range.Text = "太陽眼鏡";

    // 另存新檔以及變更副檔名的方式
    var savePath = Path.ChangeExtension(path, ".docx");
    wordApp.ActiveDocument.SaveAs2(savePath, WdSaveFormat.wdFormatXMLDocument);

    wordApp.ActiveDocument.Close();
    wordApp.Quit();
}