[C#] #9 如何用C#利用模板匯出Word檔案 - antqtech/KM GitHub Wiki

3 重要步驟

  1. 安裝word 套件
  2. 製作word 模板
  3. Word 鏈接程式碼

1. 安裝word 套件

steps-for-installing-word-library-part-1 選各自專案->加入->COM Reference

steps-for-installing-word-library-part-2 然後找"word", 打勾對於的套件

2. 製作word 模板

打開word應用程式之後, 把我們要從程式換掉的文字標籤(Bookmark), 我們會利用這個bookmark 的名字在程式碼裡使用. creating-word-document 舉例: 我想在新製造的word檔案把 ‘NameBookmark_PlaceHolder’ 的文字 換到我們對應的資料, 於是我們將那個文字標籤起來。

3. Word 鏈接程式碼

在一個API 裡面輸入以下程式碼


[HttpPost("EditingWordDocument")]
public string EditingWordDocument(ReqPerson ReqPerson)
{
   Application? app = null;
   Document? doc = null;
   try
   {
       app = new Application(); // Creating object of word application
       //app.Visible = true; // Making word application visible (useful for debugging)
       //app.DisplayAlerts = WdAlertLevel.wdAlertsNone; // supress alert messages
       doc = app.Documents.Open(@"E:\allProject\Medium\04_18_2024_word365\word365.docx", ReadOnly: false, OpenAndRepair: true);

       // Replace bookmarks with values
       doc.Bookmarks["NameBookmark"].Range.Text = ReqPerson.Name;
       doc.Bookmarks["AgeBookmark"].Range.Text = ReqPerson.Age;

       doc.SaveAs2(@"E:\allProject\Medium\04_18_2024_word365\output.docx"); // Saving the new generated document
   }
   catch (Exception e)
   {
       return e.Message;
   }
   finally
   {
       if (doc != null)
       {
           // Close Word Template without saving changes
           doc.Close(WdSaveOptions.wdDoNotSaveChanges);
       }
       if (app != null)
       {
           // close Word Application
           app.Quit();
       }
   }

記得要加入 “using Microsoft.Office.Interop.Word;


我只是把我以前寫的文章翻譯成中文 Source1-Medium