C#操作Microsoft.Office.Interop.Word類庫完整例子

東方承丘發表於2023-11-16
使用Microsoft.Office.Interop.Word類庫操作wor文件
一.準備工作
首先在工廠中,引用【Microsoft.Office.Interop.Word】,本地安裝了world,就能找到這個類庫,如下圖。Form1系統自動生成的

Form1的介面很簡單,就一個按鈕

 二 4個完整例項

4個例項,自測過的,都可用,適用很多種情況操作world。完整程式碼如下

  1 using System;
  2 using System.Collections.Generic;
  3 using System.ComponentModel;
  4 using System.Data;
  5 using System.Drawing;
  6 using System.Linq;
  7 using System.Text;
  8 using System.Threading.Tasks;
  9 using System.Windows.Forms;
 10 using MSWord = Microsoft.Office.Interop.Word;
 11 
 12 namespace _24_word_and_excel_Operator
 13 {
 14     public partial class Form1 : Form
 15     {
 16         object oMissing = System.Reflection.Missing.Value;
 17         public Form1()
 18         {
 19             InitializeComponent();
 20         }
 21 
 22         private void button1_Click(object sender, EventArgs e)
 23         {
 24             //例子1:新建一個word文件,填入自定義的內容
 25             Example1();
 26 
 27             //例子2:操作模板的例子
 28             Example2();
 29 
 30             //例子3:操作模板的例子,是例子2的一個簡單版本
 31             Example3();
 32 
 33             //例子4:複雜的例子,操作模板,標籤內填值,文件中畫表格,表格中填值。文件中填
 34             Example4(@"D:\110 - C#例項集合\100 - 例項集合\24 word and excel Operator\bin\Debug\測試文件.docx");
 35         }
 36         /// <summary>
 37         /// 新建一個word文件,填入自定義的內容
 38         /// </summary>
 39         private void Example1()
 40         {
 41             //建立一個新的Word應用程式物件
 42             Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
 43             //建立一個新的Word文件物件,就是建立一個空白的文件
 44             MSWord.Document doc = wordApp.Documents.Add();
 45             // 在新文件中新增內容
 46             MSWord.Paragraph paragraph = doc.Paragraphs.Add();
 47             paragraph.Range.Text = "Hello, World! This is a sample Word document.";
 48 
 49             // 儲存文件,注意:filePath路徑要帶上檔名
 50             string filePath = @"D:\110 - C#例項集合\100 - 例項集合\24 word and excel Operator\bin\Debug\Test\test.docx";
 51             doc.SaveAs(filePath);
 52 
 53             // 關閉Word應用程式
 54             wordApp.Quit();
 55         }
 56 
 57         /// <summary>
 58         /// 操作模板的例子
 59         /// </summary>
 60         private void Example2()
 61         {
 62             // 模板檔案路徑
 63             string templatePath = @"D:\110 - C#例項集合\100 - 例項集合\24 word and excel Operator\bin\Debug\測試文件.docx";
 64             // 生成的文件儲存路徑
 65             string newDocumentPath = @"D:\110 - C#例項集合\100 - 例項集合\24 word and excel Operator\bin\Debug\Test\例子2文件.docx";
 66 
 67             // 建立Word應用程式物件
 68             Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
 69 
 70             // 開啟模板文件
 71             Microsoft.Office.Interop.Word.Document templateDocument = wordApp.Documents.Open(templatePath);
 72 
 73             // 複製模板文件的內容
 74             templateDocument.Content.Copy();
 75 
 76             // 建立一個新的空白文件
 77             Microsoft.Office.Interop.Word.Document newDocument = wordApp.Documents.Add();
 78 
 79             // 將複製的內容貼上到新文件中
 80             newDocument.Content.Paste();
 81 
 82             // 修改新文件的內容
 83             MSWord.Paragraph paragraph = newDocument.Content.Paragraphs.Add();
 84             paragraph.Range.Text = "This is a document generated from a template.";
 85 
 86             // 儲存新文件
 87             newDocument.SaveAs(newDocumentPath);
 88 
 89             // 關閉模板文件
 90             templateDocument.Close();
 91 
 92             // 關閉Word應用程式
 93             wordApp.Quit();
 94         }
 95         /// <summary>
 96         /// 操作模板的例子,是例子2的一個簡單版本
 97         /// </summary>
 98         /// <param name="templatePath"></param>
 99         /// <param name="outputPath"></param>
100         public void Example3()
101         {
102             string templatePath = @"D:\110 - C#例項集合\100 - 例項集合\24 word and excel Operator\bin\Debug\測試文件.docx";
103             string outputPath = @"D:\110 - C#例項集合\100 - 例項集合\24 word and excel Operator\bin\Debug\Test\例子3的文件.docx";
104 
105             // 建立Word應用程式物件
106             Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
107             // 開啟模板文件
108             MSWord.Document wordDoc = wordApp.Documents.Open(templatePath);
109             {
110                 //這裡就是要幹什麼事了,替換文字,新增內容等操作
111                 // 替換模板中的文字
112                 FindAndReplace(wordDoc, "要替換的文字", "替換後的文字");
113                 // 修改新文件的內容
114                 MSWord.Paragraph paragraph = wordDoc.Content.Paragraphs.Add();
115                 paragraph.Range.Text = "This is a document generated from a template.";
116             }
117 
118             // 儲存為新文件
119             wordDoc.SaveAs2(outputPath);
120             // 關閉Word應用程式物件
121             wordApp.Quit();
122         }
123 
124         private void FindAndReplace(MSWord.Document doc, string findText, string replaceText)
125         {
126             // 將模板設為可編輯
127             doc.Activate();
128 
129             // 執行查詢和替換操作
130             // 可以使用其他查詢和替換方法,例如使用Range物件
131             object findObj = findText;
132             object replaceObj = replaceText;
133             object missingObj = Type.Missing;
134             doc.Content.Find.Execute(ref findObj, ref missingObj, ref missingObj, ref missingObj, ref missingObj,
135                 ref missingObj, ref missingObj, ref missingObj, ref missingObj, ref replaceObj, ref missingObj,
136                 ref missingObj, ref missingObj, ref missingObj, ref missingObj);
137         }
138         private void Example4(string strPath)
139         {
140             object oTemplate = strPath;
141             MSWord.Application wordApp = new MSWord.Application();// 建立一個新的Word應用程式物件
142             wordApp.Visible = true;
143             MSWord.Document oDoc = wordApp.Documents.Add(ref oTemplate, ref oMissing, ref oMissing, ref oMissing);// 建立一個新的Word文件物件
144 
145             //填寫標籤
146             object[] bookMark = new object[3];
147             bookMark[0] = "Test1";
148             bookMark[1] = "Test2";
149             oDoc.Bookmarks.get_Item(ref bookMark[0]).Range.Text = "第1個標籤";
150             oDoc.Bookmarks.get_Item(ref bookMark[1]).Range.Text = "第2個標籤";
151 
152 
153             //定義一個Word中的表格物件
154             oDoc.Paragraphs.Last.Range.Text = "直接接入式(正向電能)";
155             //用於在Word文件中進行特定的文字插入和調整操作
156             object unite = MSWord.WdUnits.wdStory;//這表示將選擇操作的範圍設為整個文件
157             oDoc.Content.InsertAfter("\n");//在文件的內容後面插入一個換行符("\n"),即實現在文件末尾新增一個空行
158             wordApp.Selection.EndKey(ref unite, ref oMissing);//將選擇操作的焦點移動到文件的結尾,即將游標定位在文件的最後一行。
159             wordApp.Selection.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphLeft;//將游標所在處的段落對齊方式設定為左對齊。
160             object WdLine2 = MSWord.WdUnits.wdLine;//換一行;這表示將選擇操作的單位設為行。
161             wordApp.Selection.MoveDown(ref WdLine2, 6, ref oMissing);//將當前選擇向下移動6行。
162 
163             int iRow = 5;
164             int iColumn = 3;
165             MSWord.Table table = oDoc.Tables.Add(wordApp.Selection.Range, iRow, iColumn, ref oMissing, ref oMissing);
166             table.Borders.Enable = 1;
167             for (int i = 1; i < iRow + 1; i++)
168             {
169                 if (i == 1)
170                 {
171                     table.Cell(i, 1).Range.Text = "電壓(V)";
172                     table.Cell(i, 2).Range.Text = "電流(A)";
173                     table.Cell(i, 3).Range.Text = "電能誤差(%)";
174                 }
175                 else
176                 {
177                     table.Cell(i, 1).Range.Text = (i + 1).ToString();
178                     table.Cell(i, 2).Range.Text = (i + 2).ToString();
179                     table.Cell(i, 3).Range.Text = (i + 3).ToString();
180                 }
181             }
182             //該行程式碼的作用是將表格中所有段落的對齊方式設定為居中對齊
183             table.Range.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;
184 
185             //文件最後填寫文字
186             oDoc.Paragraphs.Last.Range.Text = "文件最後的位置:\n\r";
187 
188             string docname = string.Empty;
189             docname = $"文件名稱";
190 
191             //彈出儲存檔案對話方塊,儲存生成的Word
192             SaveFileDialog sfd = new SaveFileDialog
193             {
194                 Filter = "Word Document(*.docx)|*.docx",
195                 DefaultExt = "Word Document(*.docx)|*.docx",
196                 FileName = docname
197             };
198             if (sfd.ShowDialog() == DialogResult.OK)
199             {
200                 object filename = sfd.FileName;
201                 oDoc.SaveAs(ref filename, ref oMissing, ref oMissing, ref oMissing,
202                 ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
203                 ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
204                 ref oMissing, ref oMissing);
205 
206                 // 關閉Word應用程式物件
207                 wordApp.Quit();
208             }
209         }
210     }
211 }

 

三 程式碼分析解讀 (重點部分)

 例子1:適用的情況是,程式碼建立一個新的world文件的情況

注意:無論是例子1,例子2,例子3,其中的路徑,要填寫自己本地的路徑。

 

 

例子2和例子3:

兩個例子都是操作world模板的,例子2程式碼複雜寫,例子3精簡寫。效果都是一樣的。

例子3中,SaveAs2 方法是 SaveAs 方法的擴充套件版本,支援更多的儲存選項和引數。例子3中, wordDoc.SaveAs2(outputPath);中 outputPath是指定要儲存文件的完整路徑,包括檔名和副檔名。效果如下圖

 

例子4:這個例子稍微複雜一下,設計文件中先插入好標籤,標籤地方填值,文件中畫出表格,表格中填值,文件最後追加文件等操作。

模板文件的標籤如下圖:

例子4的效果如下圖:

 

 

 

 

 

 

相關文章