C#操作Word的超詳細總結
阿新 • • 發佈:2019-02-08
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Runtime.InteropServices; 5 using System.Text; 6 using MSWord = Microsoft.Office.Interop.Word; 7 using System.IO; 8 using System.Reflection; 9 10 namespace Console_WordSkill_All 11 { 12 classProgram 13 { 14 static void Main(string[] args) 15 { 16 object path; //檔案路徑變數 17 string strContent; //文字內容變數 18 MSWord.Application wordApp; //Word應用程式變數 19 MSWord.Document wordDoc; //Word文件變數 20 21 path = Environment.CurrentDirectory + "\\MyWord_Print.doc"; 22 wordApp = new MSWord.ApplicationClass(); //初始化 23 24 wordApp.Visible = true;//使文件可見 25 26 //如果已存在,則刪除 27 if (File.Exists((string)path)) 28 {29 File.Delete((string)path); 30 } 31 32 //由於使用的是COM庫,因此有許多變數需要用Missing.Value代替 33 Object Nothing = Missing.Value; 34 wordDoc = wordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing); 35 36 #region 頁面設定、頁首圖片和文字設定,最後跳出頁首設定 37 38 //頁面設定 39 wordDoc.PageSetup.PaperSize = MSWord.WdPaperSize.wdPaperA4;//設定紙張樣式為A4紙 40 wordDoc.PageSetup.Orientation = MSWord.WdOrientation.wdOrientPortrait;//排列方式為垂直方向 41 wordDoc.PageSetup.TopMargin = 57.0f; 42 wordDoc.PageSetup.BottomMargin = 57.0f; 43 wordDoc.PageSetup.LeftMargin = 57.0f; 44 wordDoc.PageSetup.RightMargin = 57.0f; 45 wordDoc.PageSetup.HeaderDistance = 30.0f;//頁首位置 46 47 //設定頁首 48 wordApp.ActiveWindow.View.Type = MSWord.WdViewType.wdNormalView;//普通檢視(即頁面檢視)樣式 49 wordApp.ActiveWindow.View.SeekView = MSWord.WdSeekView.wdSeekPrimaryHeader;//進入頁首設定,其中頁首邊距在頁面設定中已完成 50 wordApp.Selection.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphRight;//頁首中的文字右對齊 51 52 53 //插入頁首圖片(測試結果圖片未插入成功) 54 wordApp.Selection.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter; 55 string headerfile = @"C:\Users\xiahui\Desktop\OficeProgram\3.jpg"; 56 MSWord.InlineShape shape1 = wordApp.ActiveWindow.ActivePane.Selection.InlineShapes.AddPicture(headerfile, ref Nothing, ref Nothing, ref Nothing); 57 shape1.Height = 5;//強行設定貌似無效,圖片沒有按設定的縮放——圖片的比例並沒有改變。 58 shape1.Width = 20; 59 wordApp.ActiveWindow.ActivePane.Selection.InsertAfter(" 文件頁首");//在頁首的圖片後面追加幾個字 60 61 //去掉頁首的橫線 62 wordApp.ActiveWindow.ActivePane.Selection.ParagraphFormat.Borders[MSWord.WdBorderType.wdBorderBottom].LineStyle = MSWord.WdLineStyle.wdLineStyleNone; 63 wordApp.ActiveWindow.ActivePane.Selection.Borders[MSWord.WdBorderType.wdBorderBottom].Visible = false; 64 wordApp.ActiveWindow.ActivePane.View.SeekView = MSWord.WdSeekView.wdSeekMainDocument;//退出頁首設定 65 #endregion 66 67 #region 頁碼設定並新增頁碼 68 69 //為當前頁新增頁碼 70 MSWord.PageNumbers pns = wordApp.Selection.Sections[1].Headers[MSWord.WdHeaderFooterIndex.wdHeaderFooterEvenPages].PageNumbers;//獲取當前頁的號碼 71 pns.NumberStyle = MSWord.WdPageNumberStyle.wdPageNumberStyleNumberInDash;//設定頁碼的風格,是Dash形還是圓形的 72 pns.HeadingLevelForChapter = 0; 73 pns.IncludeChapterNumber = false; 74 pns.RestartNumberingAtSection = false; 75 pns.StartingNumber = 0; //開始頁頁碼? 76 object pagenmbetal = MSWord.WdPageNumberAlignment.wdAlignPageNumberCenter;//將號碼設定在中間 77 object first = true; 78 wordApp.Selection.Sections[1].Footers[MSWord.WdHeaderFooterIndex.wdHeaderFooterEvenPages].PageNumbers.Add(ref pagenmbetal, ref first); 79 80 #endregion 81 82 #region 行間距與縮排、文字字型、字號、加粗、斜體、顏色、下劃線、下劃線顏色設定 83 84 wordApp.Selection.ParagraphFormat.LineSpacing = 16f;//設定文件的行間距 85 wordApp.Selection.ParagraphFormat.FirstLineIndent = 30;//首行縮排的長度 86 //寫入普通文字 87 strContent = "我是普通文字\n"; 88 wordDoc.Paragraphs.Last.Range.Text = strContent; 89 90 wordDoc.Paragraphs.Last.Range.Text = "我再加一行試試,這裡不加‘\\n‘"; 91 //直接新增段,不是覆蓋( += ) 92 wordDoc.Paragraphs.Last.Range.Text += "不會覆蓋的,"; 93 94 //新增在此段的文字後面,不是新段落 95 wordDoc.Paragraphs.Last.Range.InsertAfter("這是後面的內容\n"); 96 97 //將文件的前4個字替換成"哥是替換文字",並將其顏色設為紅色 98 object start = 0; 99 object end = 4; 100 MSWord.Range rang = wordDoc.Range(ref start, ref end); 101 rang.Font.Color = MSWord.WdColor.wdColorRed; 102 rang.Text = "哥是替換文字"; 103 wordDoc.Range(ref start, ref end); 104 105 //寫入黑體文字 106 object unite = MSWord.WdUnits.wdStory; 107 wordApp.Selection.EndKey(ref unite, ref Nothing);//將游標移到文字末尾 108 wordApp.Selection.ParagraphFormat.FirstLineIndent = 0;//取消首行縮排的長度 109 strContent = "這是黑體文字\n"; 110 wordDoc.Paragraphs.Last.Range.Font.Name = "黑體"; 111 wordDoc.Paragraphs.Last.Range.Text = strContent; 112 113 //寫入加粗文字 114 strContent = "這是粗體文字\n"; // 115 wordApp.Selection.EndKey(ref unite, ref Nothing);//這一句不加,有時候好像也不出問題,不過還是加了安全 116 wordDoc.Paragraphs.Last.Range.Font.Bold = 1; 117 wordDoc.Paragraphs.Last.Range.Text = strContent; 118 119 //寫入15號字型文字 120 strContent = "我這個文字的字號是15號,而且是宋體\n"; 121 wordApp.Selection.EndKey(ref unite, ref Nothing); 122 wordDoc.Paragraphs.Last.Range.Font.Size = 15; 123 wordDoc.Paragraphs.Last.Range.Font.Name = "宋體"; 124 wordDoc.Paragraphs.Last.Range.Text = strContent; 125 126 //寫入斜體文字 127 strContent = "我是斜體字文字\n"; 128 wordApp.Selection.EndKey(ref unite, ref Nothing); 129 wordDoc.Paragraphs.Last.Range.Font.Italic = 1; 130 wordDoc.Paragraphs.Last.Range.Text = strContent; 131 132 //寫入藍色文字 133 strContent = "我是藍色的文字\n"; 134 wordApp.Selection.EndKey(ref unite, ref Nothing); 135 wordDoc.Paragraphs.Last.Range.Font.Color = MSWord.WdColor.wdColorBlue; 136 wordDoc.Paragraphs.Last.Range.Text = strContent; 137 138 //寫入下劃線文字 139 strContent = "我是下劃線文字\n"; 140 wordApp.Selection.EndKey(ref unite, ref Nothing); 141 wordDoc.Paragraphs.Last.Range.Font.Underline = MSWord.WdUnderline.wdUnderlineThick; 142 wordDoc.Paragraphs.Last.Range.Text = strContent; 143 144 //寫入紅色下畫線文字 145 strContent = "我是點線下劃線,並且下劃線是紅色的\n"; 146 wordApp.Selection.EndKey(ref unite, ref Nothing); 147 wordDoc.Paragraphs.Last.Range.Font.Underline = MSWord.WdUnderline.wdUnderlineDottedHeavy; 148 wordDoc.Paragraphs.Last.Range.Font.UnderlineColor = MSWord.WdColor.wdColorRed; 149 wordDoc.Paragraphs.Last.Range.Text = strContent; 150 151 //取消下劃線,並且將字號調整為12號 152 strContent = "我他媽不要下劃線了,並且設定字號為12號,黑色不要斜體\n"; 153 wordApp.Selection.EndKey(ref unite, ref Nothing); 154 wordDoc.Paragraphs.Last.Range.Font.Size = 12; 155 wordDoc.Paragraphs.Last.Range.Font.Underline = MSWord.WdUnderline.wdUnderlineNone; 156 wordDoc.Paragraphs.Last.Range.Font.Color = MSWord.WdColor.wdColorBlack; 157 wordDoc.Paragraphs.Last.Range.Font.Italic = 0; 158 wordDoc.Paragraphs.Last.Range.Text = strContent; 159 160 161 #endregion 162 163 164 #region 插入圖片、居中顯示,設定圖片的絕對尺寸和縮放尺寸,並給圖片新增標題 165 166 wordApp.Selection.EndKey(ref unite, ref Nothing); //將游標移動到文件末尾 167 //圖片檔案的路徑 168 string filename = Environment.CurrentDirectory + "\\6.jpg"; 169 //要向Word文件中插入圖片的位置 170 Object range = wordDoc.Paragraphs.Last.Range; 171 //定義該插入的圖片是否為外部連結 172 Object linkToFile = false; //預設,這裡貌似設定為bool型別更清晰一些 173 //定義要插入的圖片是否隨Word文件一起儲存 174 Object saveWithDocument = true; //預設 175 //使用InlineShapes.AddPicture方法(【即“嵌入型”】)插入圖片 176 wordDoc.InlineShapes.AddPicture(filename, ref linkToFile, ref saveWithDocument, ref range); 177 wordApp.Selection.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;//居中顯示圖片 178 179 //設定圖片寬高的絕對大小 180 181 //wordDoc.InlineShapes[1].Width = 200; 182 //wordDoc.InlineShapes[1].Height = 150; 183 //按比例縮放大小 184 185 wordDoc.InlineShapes[1].ScaleWidth = 20;//縮小到20% ? 186 wordDoc.InlineShapes[1].ScaleHeight = 20; 187 188 //在圖下方居中新增圖片標題 189 190 wordDoc.Content.InsertAfter("\n");//這一句與下一句的順序不能顛倒,原因還沒搞透 191 wordApp.Selection.EndKey(ref unite, ref Nothing); 192 wordApp.Selection.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter; 193 wordApp.Selection.Font.Size = 10;//字型大小 194 wordApp.Selection.TypeText("圖1 測試圖片\n"); 195 196 #endregion 197 198 #region 新增表格、填充資料、設定表格行列寬高、合併單元格、新增表頭斜線、給單元格新增圖片 199 wordDoc.Content.InsertAfter("\n");//這一句與下一句的順序不能顛倒,原因還沒搞透 200 wordApp.Selection.EndKey(ref unite, ref Nothing); //將游標移動到文件末尾 201 wordApp.Selection.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphLeft; 202 //object WdLine2 = MSWord.WdUnits.wdLine;//換一行; 203 //wordApp.Selection.MoveDown(ref WdLine2, 6, ref Nothing);//向下跨15行輸入表格,這樣表格就在文字下方了,不過這是非主流的方法 204 205 //設定表格的行數和列數 206 int tableRow = 6; 207 int tableColumn = 6; 208 209 //定義一個Word中的表格物件 210 MSWord.Table table = wordDoc.Tables.Add(wordApp.Selection.Range, 211 tableRow, tableColumn, ref Nothing, ref Nothing); 212 213 //預設建立的表格沒有邊框,這裡修改其屬性,使得建立的表格帶有邊框 214 table.Borders.Enable = 1;//這個值可以設定得很大,例如5、13等等 215 216 //表格的索引是從1開始的。 217 wordDoc.Tables[1].Cell(1, 1).Range.Text = "列\n行"; 218 for (int i = 1; i < tableRow; i++) 219 { 220 for (int j = 1; j < tableColumn; j++) 221 { 222 if (i == 1) 223 { 224 table.Cell(i, j + 1).Range.Text = "Column " + j;//填充每列的標題 225 } 226 if (j == 1) 227 { 228 table.Cell(i + 1, j).Range.Text = "Row " + i; //填充每行的標題 229 } 230 table.Cell(i + 1, j + 1).Range.Text = i + "行 " + j + "列"; //填充表格的各個小格子 231 } 232 } 233 234 235 //新增行 236 table.Rows.Add(ref Nothing); 237 table.Rows[tableRow + 1].Height = 35;//設定新增加的這行表格的高度 238 //向新新增的行的單元格中新增圖片 239 string FileName = Environment.CurrentDirectory + "\\6.jpg";//圖片所在路徑 240 object LinkToFile = false; 241 object SaveWithDocument = true; 242 object Anchor = table.Cell(tableRow + 1, tableColumn).Range;//選中要新增圖片的單元格 243 wordDoc.Application.ActiveDocument.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref Anchor); 244 245 //由於是本文件的第2張圖,所以這裡是InlineShapes[2] 246 wordDoc.Application.ActiveDocument.InlineShapes[2].Width = 50;//圖片寬度 247 wordDoc.Application.ActiveDocument.InlineShapes[2].Height = 35;//圖片高度 248 249 // 將圖片設定為四周環繞型 250 MSWord.Shape s = wordDoc.Application.ActiveDocument.InlineShapes[2].ConvertToShape(); 251 s.WrapFormat.Type = MSWord.WdWrapType.wdWrapSquare; 252 253 254 //設定table樣式 255 table.Rows.HeightRule = MSWord.WdRowHeightRule.wdRowHeightAtLeast;//高度規則是:行高有最低值下限? 256 table.Rows.Height = wordApp.CentimetersToPoints(float.Parse("0.8"));// 257 258 table.Range.Font.Size = 10.5F; 259 table.Range.Font.Bold = 0; 260 261 table.Range.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphCenter;//表格文字居中 262 table.Range.Cells.VerticalAlignment = MSWord.WdCellVerticalAlignment.wdCellAlignVerticalBottom;//文字垂直貼到底部 263 //設定table邊框樣式 264 table.Borders.OutsideLineStyle = MSWord.WdLineStyle.wdLineStyleDouble;//表格外框是雙線 265 table.Borders.InsideLineStyle = MSWord.WdLineStyle.wdLineStyleSingle;//表格內框是單線 266 267 table.Rows[1].Range.Font.Bold = 1;//加粗 268 table.Rows[1].Range.Font.Size = 12F; 269 table.Cell(1, 1).Range.Font.Size = 10.5F; 270 wordApp.Selection.Cells.Height = 30;//所有單元格的高度 271 272 //除第一行外,其他行的行高都設定為20 273 for (int i = 2; i <= tableRow; i++) 274 { 275 table.Rows[i].Height = 20; 276 } 277 278 //將表格左上角的單元格里的文字(“行” 和 “列”)居右 279 table.Cell(1, 1).Range.ParagraphFormat.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphRight; 280 //將表格左上角的單元格里面下面的“列”字移到左邊,相比上一行就是將ParagraphFormat改成了Paragraphs[2].Format 281 table.Cell(1, 1).Range.Paragraphs[2].Format.Alignment = MSWord.WdParagraphAlignment.wdAlignParagraphLeft; 282 283 table.Columns[1].Width = 50;//將第 1列寬度設定為50 284 285 //將其他列的寬度都設定為75 286 for (int i = 2; i <= tableColumn; i++) 287 { 288 table.Columns[i].Width = 75; 289 } 290 291 292 //新增表頭斜線,並設定表頭的樣式 293 table.Cell(1, 1).Borders[MSWord.WdBorderType.wdBorderDiagonalDown].Visible = true; 294 table.Cell(1, 1).Borders[MSWord.WdBorderType.wdBorderDiagonalDown].Color = MSWord.WdColor.wdColorRed; 295 table.Cell(1, 1).Borders[MSWord.WdBorderType.wdBorderDiagonalDown].LineWidth = MSWord.WdLineWidth.wdLineWidth150pt; 296 297 //合併單元格 298 table.Cell(4, 4).Merge(table.Cell(4, 5));//橫向合併 299 300 table.Cell(2, 3).Merge(table.Cell(4, 3));//縱向合併,合併(2,3),(3,3),(4,3) 301 302 #endregion 303 304 wordApp.Selection.EndKey(ref unite, ref Nothing); //將游標移動到文件末尾 305 306 wordDoc.Content.InsertAfter("\n"); 307 wordDoc.Content.InsertAfter("就寫這麼多,算了吧!2016.09.27"); 308 309 310 311 //WdSaveFormat為Word 2003文件的儲存格式 312 object format = MSWord.WdSaveFormat.wdFormatDocument;// office 2007就是wdFormatDocumentDefault 313 //將wordDoc文件物件的內容儲存為DOCX文件 314 wordDoc.SaveAs(ref path, ref format, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing); 315 //關閉wordDoc文件物件 316 317 //看是不是要列印 318 //wordDoc.PrintOut(); 319 320 321 322 wordDoc.Close(ref Nothing, ref Nothing, ref Nothing); 323 //關閉wordApp元件物件 324 wordApp.Quit(ref Nothing, ref Nothing, ref Nothing); 325 Console.WriteLine(path + " 建立完畢!"); 326 Console.ReadKey(); 327 328 329 //我還要開啟這個文件玩玩 330 MSWord.Application app = new MSWord.Application(); 331 MSWord.Document doc = null; 332 try 333 { 334 335 object unknow = Type.Missing; 336 app.Visible = true; 337 string str = Environment.CurrentDirectory + "\\MyWord_Print.doc"; 338 object file = str; 339 doc = app.Documents.Open(ref file, 340 ref unknow, ref unknow, ref unknow, ref unknow, 341 ref unknow, ref unknow, ref unknow, ref unknow, 342 ref unknow, ref unknow, ref unknow, ref unknow, 343 ref unknow, ref unknow, ref unknow); 344 string temp = doc.Paragraphs[1].Range.Text.Trim(); 345 Console.WriteLine("你他媽輸出temp幹嘛?"); 346 } 347 catch (Exception ex) 348 { 349 Console.WriteLine(ex.Message); 350 } 351 wordDoc = doc; 352 wordDoc.Paragraphs.Last.Range.Text += "我真的不打算再寫了,就寫這麼多吧"; 353 354 Console.ReadKey(); 355 } 356 357 } 358 }