1 public class WordOperate 2 { 3 4 #region 新建Word文档 5 /// <summary> 6 /// 动态生成Word文档并填充内容 7 /// </summary> 8 /// <param name="dir">文档目录</param> 9 /// <param name="fileName">文档名</param> 10 /// <returns>返回自定义信息</returns> 11 public static bool CreateWordFile(string dir, string fileName) 12 { 13 try 14 { 15 Object oMissing = System.Reflection.Missing.Value; 16 17 if (!Directory.Exists(dir)) 18 { 19 //创建文件所在目录 20 Directory.CreateDirectory(dir); 21 } 22 //创建Word文档(Microsoft.Office.Interop.Word) 23 Microsoft.Office.Interop.Word._Application WordApp = new Application(); 24 WordApp.Visible = true; 25 Microsoft.Office.Interop.Word._Document WordDoc = WordApp.Documents.Add( 26 ref oMissing, ref oMissing, ref oMissing, ref oMissing); 27 28 //保存 29 object filename = dir + fileName; 30 WordDoc.SaveAs(ref filename, ref oMissing, ref oMissing, ref oMissing, ref oMissing, 31 ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, 32 ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); 33 WordDoc.Close(ref oMissing, ref oMissing, ref oMissing); 34 WordApp.Quit(ref oMissing, ref oMissing, ref oMissing); 35 return true; 36 } 37 catch (Exception e) 38 { 39 Console.WriteLine(e.Message); 40 Console.WriteLine(e.StackTrace); 41 return false; 42 } 43 } 44 45 #endregion 新建Word文档 46 47 #region 给word文档添加页眉页脚 48 /// <summary> 49 /// 给word文档添加页眉 50 /// </summary> 51 /// <param name="filePath">文件名</param> 52 /// <returns></returns> 53 public static bool AddPageHeaderFooter(string filePath) 54 { 55 try 56 { 57 Object oMissing = System.Reflection.Missing.Value; 58 Microsoft.Office.Interop.Word._Application WordApp = new Application(); 59 WordApp.Visible = true; 60 object filename = filePath; 61 Microsoft.Office.Interop.Word._Document WordDoc = WordApp.Documents.Open(ref filename, ref oMissing, 62 ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, 63 ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); 64 65 ////添加页眉方法一: 66 //WordApp.ActiveWindow.View.Type = WdViewType.wdOutlineView; 67 //WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekPrimaryHeader; 68 //WordApp.ActiveWindow.ActivePane.Selection.InsertAfter( "**公司" );//页眉内容 69 70 ////添加页眉方法二: 71 if (WordApp.ActiveWindow.ActivePane.View.Type == WdViewType.wdNormalView || 72 WordApp.ActiveWindow.ActivePane.View.Type == WdViewType.wdOutlineView) 73 { 74 WordApp.ActiveWindow.ActivePane.View.Type = WdViewType.wdPrintView; 75 } 76 WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekCurrentPageHeader; 77 WordApp.Selection.HeaderFooter.LinkToPrevious = false; 78 WordApp.Selection.HeaderFooter.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; 79 WordApp.Selection.HeaderFooter.Range.Text = "页眉内容"; 80 81 WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekCurrentPageFooter; 82 WordApp.Selection.HeaderFooter.LinkToPrevious = false; 83 WordApp.Selection.HeaderFooter.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; 84 WordApp.ActiveWindow.ActivePane.Selection.InsertAfter("页脚内容"); 85 86 //跳出页眉页脚设置 87 WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekMainDocument; 88 89 //保存 90 WordDoc.Save(); 91 WordDoc.Close(ref oMissing, ref oMissing, ref oMissing); 92 WordApp.Quit(ref oMissing, ref oMissing, ref oMissing); 93 return true; 94 } 95 catch (Exception e) 96 { 97 Console.WriteLine(e.Message); 98 Console.WriteLine(e.StackTrace); 99 return false; 100 } 101 } 102 #endregion 给word文档添加页眉页脚 103 104 #region 设置文档格式并添加文本内容 105 /// <summary> 106 /// 设置文档格式并添加文本内容 107 /// </summary> 108 /// <param name="filePath">文件名</param> 109 /// <returns></returns> 110 public static bool AddContent(string filePath) 111 { 112 try 113 { 114 Object oMissing = System.Reflection.Missing.Value; 115 Microsoft.Office.Interop.Word._Application WordApp = new Application(); 116 WordApp.Visible = true; 117 object filename = filePath; 118 Microsoft.Office.Interop.Word._Document WordDoc = WordApp.Documents.Open(ref filename, ref oMissing, 119 ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, 120 ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); 121 122 //设置居左 123 WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft; 124 125 //设置文档的行间距 126 WordApp.Selection.ParagraphFormat.LineSpacing = 15f; 127 //插入段落 128 //WordApp.Selection.TypeParagraph(); 129 Microsoft.Office.Interop.Word.Paragraph para; 130 para = WordDoc.Content.Paragraphs.Add(ref oMissing); 131 //正常格式 132 para.Range.Text = "This is paragraph 1"; 133 //para.Range.Font.Bold = 2; 134 //para.Range.Font.Color = WdColor.wdColorRed; 135 //para.Range.Font.Italic = 2; 136 para.Range.InsertParagraphAfter(); 137 138 para.Range.Text = "This is paragraph 2"; 139 para.Range.InsertParagraphAfter(); 140 141 //插入Hyperlink 142 Microsoft.Office.Interop.Word.Selection mySelection = WordApp.ActiveWindow.Selection; 143 mySelection.Start = 9999; 144 mySelection.End = 9999; 145 Microsoft.Office.Interop.Word.Range myRange = mySelection.Range; 146 147 Microsoft.Office.Interop.Word.Hyperlinks myLinks = WordDoc.Hyperlinks; 148 object linkAddr = @"http://www.cnblogs.com/lantionzy"; 149 Microsoft.Office.Interop.Word.Hyperlink myLink = myLinks.Add(myRange, ref linkAddr, 150 ref oMissing); 151 WordApp.ActiveWindow.Selection.InsertAfter("\n"); 152 153 //落款 154 WordDoc.Paragraphs.Last.Range.Text = "文档创建时间:" + DateTime.Now.ToString(); 155 WordDoc.Paragraphs.Last.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight; 156 157 //保存 158 WordDoc.Save(); 159 WordDoc.Close(ref oMissing, ref oMissing, ref oMissing); 160 WordApp.Quit(ref oMissing, ref oMissing, ref oMissing); 161 return true; 162 } 163 catch (Exception e) 164 { 165 Console.WriteLine(e.Message); 166 Console.WriteLine(e.StackTrace); 167 return false; 168 } 169 } 170 171 #endregion 设置文档格式并添加文本内容 172 173 #region 文档中添加图片 174 /// <summary> 175 /// 文档中添加图片 176 /// </summary> 177 /// <param name="filePath">word文件名</param> 178 /// <param name="picPath">picture文件名</param> 179 /// <returns></returns> 180 public static bool AddPicture(string filePath, string picPath) 181 { 182 try 183 { 184 Object oMissing = System.Reflection.Missing.Value; 185 Microsoft.Office.Interop.Word._Application WordApp = new Application(); 186 WordApp.Visible = true; 187 object filename = filePath; 188 Microsoft.Office.Interop.Word._Document WordDoc = WordApp.Documents.Open(ref filename, ref oMissing, 189 ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, 190 ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); 191 192 //移动光标文档末尾 193 object count = WordDoc.Paragraphs.Count; 194 object WdLine = Microsoft.Office.Interop.Word.WdUnits.wdParagraph; 195 WordApp.Selection.MoveDown(ref WdLine, ref count, ref oMissing);//移动焦点 196 WordApp.Selection.TypeParagraph();//插入段落 197 198 object LinkToFile = false; 199 object SaveWithDocument = true; 200 object Anchor = WordDoc.Application.Selection.Range; 201 WordDoc.Application.ActiveDocument.InlineShapes.AddPicture(picPath, ref LinkToFile, ref SaveWithDocument, ref Anchor); 202 203 //保存 204 WordDoc.Save(); 205 WordDoc.Close(ref oMissing, ref oMissing, ref oMissing); 206 WordApp.Quit(ref oMissing, ref oMissing, ref oMissing); 207 return true; 208 } 209 catch (Exception e) 210 { 211 Console.WriteLine(e.Message); 212 Console.WriteLine(e.StackTrace); 213 return false; 214 } 215 } 216 #endregion 文档中添加图片 217 218 #region 表格处理(插入表格、设置格式、填充内容) 219 /// <summary> 220 /// 表格处理 221 /// </summary> 222 /// <param name="filePath">word文件名</param> 223 /// <returns></returns> 224 public static bool AddTable(string filePath) 225 { 226 try 227 { 228 Object oMissing = System.Reflection.Missing.Value; 229 Microsoft.Office.Interop.Word._Application WordApp = new Application(); 230 WordApp.Visible = true; 231 object filename = filePath; 232 Microsoft.Office.Interop.Word._Document WordDoc = WordApp.Documents.Open(ref filename, ref oMissing, ref oMissing, ref oMissing, ref oMissing, 233 ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); 234 235 //插入表格 236 Microsoft.Office.Interop.Word.Table newTable = WordDoc.Tables.Add(WordApp.Selection.Range, 12, 3, ref oMissing, ref oMissing); 237 //设置表格 238 newTable.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleThickThinLargeGap; 239 newTable.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle; 240 newTable.Columns[1].Width = 100f; 241 newTable.Columns[2].Width = 220f; 242 newTable.Columns[3].Width = 105f; 243 244 //填充表格内容 245 newTable.Cell(1, 1).Range.Text = "我的简历"; 246 //设置单元格中字体为粗体 247 newTable.Cell(1, 1).Range.Bold = 2; 248 249 //合并单元格 250 newTable.Cell(1, 1).Merge(newTable.Cell(1, 3)); 251 252 //垂直居中 253 WordApp.Selection.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; 254 //水平居中 255 WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter; 256 257 //填充表格内容 258 newTable.Cell(2, 1).Range.Text = "座右铭:..."; 259 //设置单元格内字体颜色 260 newTable.Cell(2, 1).Range.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorDarkBlue; 261 //合并单元格 262 newTable.Cell(2, 1).Merge(newTable.Cell(2, 3)); 263 WordApp.Selection.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter; 264 265 //填充表格内容 266 newTable.Cell(3, 1).Range.Text = "姓名:"; 267 newTable.Cell(3, 2).Range.Text = "雷鑫"; 268 //纵向合并单元格 269 newTable.Cell(3, 3).Select(); 270 //选中一行 271 object moveUnit = Microsoft.Office.Interop.Word.WdUnits.wdLine; 272 object moveCount = 3; 273 object moveExtend = Microsoft.Office.Interop.Word.WdMovementType.wdExtend; 274 WordApp.Selection.MoveDown(ref moveUnit, ref moveCount, ref moveExtend); 275 WordApp.Selection.Cells.Merge(); 276 277 //表格中插入图片 278 string pictureFileName = System.IO.Directory.GetCurrentDirectory() + @"\picture.jpg"; 279 object LinkToFile = false; 280 object SaveWithDocument = true; 281 object Anchor = WordDoc.Application.Selection.Range; 282 WordDoc.Application.ActiveDocument.InlineShapes.AddPicture(pictureFileName, ref LinkToFile, ref SaveWithDocument, ref Anchor); 283 //图片宽度 284 WordDoc.Application.ActiveDocument.InlineShapes[1].Width = 100f; 285 //图片高度 286 WordDoc.Application.ActiveDocument.InlineShapes[1].Height = 100f; 287 //将图片设置为四周环绕型 288 Microsoft.Office.Interop.Word.Shape s = WordDoc.Application.ActiveDocument.InlineShapes[1].ConvertToShape(); 289 s.WrapFormat.Type = Microsoft.Office.Interop.Word.WdWrapType.wdWrapSquare; 290 291 newTable.Cell(12, 1).Range.Text = "备注:"; 292 newTable.Cell(12, 1).Merge(newTable.Cell(12, 3)); 293 //在表格中增加行 294 WordDoc.Content.Tables[1].Rows.Add(ref oMissing); 295 296 //保存 297 WordDoc.Save(); 298 WordDoc.Close(ref oMissing, ref oMissing, ref oMissing); 299 WordApp.Quit(ref oMissing, ref oMissing, ref oMissing); 300 return true; 301 } 302 catch (Exception e) 303 { 304 Console.WriteLine(e.Message); 305 Console.WriteLine(e.StackTrace); 306 return false; 307 } 308 } 309 #endregion #region 表格处理 310 311 #region 把Word文档转化为Html文件 312 /// <summary> 313 /// 把Word文档转化为Html文件 314 /// </summary> 315 /// <param name="wordFileName">word文件名</param> 316 /// <param name="htmlFileName">要保存的html文件名</param> 317 /// <returns></returns> 318 public static bool WordToHtml(string wordFileName, string htmlFileName) 319 { 320 try 321 { 322 Object oMissing = System.Reflection.Missing.Value; 323 Microsoft.Office.Interop.Word._Application WordApp = new Application(); 324 WordApp.Visible = true; 325 object filename = wordFileName; 326 Microsoft.Office.Interop.Word._Document WordDoc = WordApp.Documents.Open(ref filename, ref oMissing, 327 ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, 328 ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); 329 330 // Type wordType = WordApp.GetType(); 331 // 打开文件 332 Type docsType = WordApp.Documents.GetType(); 333 // 转换格式,另存为 334 Type docType = WordDoc.GetType(); 335 object saveFileName = htmlFileName; 336 docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod, null, WordDoc, 337 new object[] { saveFileName, Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatHTML }); 338 339 #region 其它格式: 340 ///wdFormatHTML 341 ///wdFormatDocument 342 ///wdFormatDOSText 343 ///wdFormatDOSTextLineBreaks 344 ///wdFormatEncodedText 345 ///wdFormatRTF 346 ///wdFormatTemplate 347 ///wdFormatText 348 ///wdFormatTextLineBreaks 349 ///wdFormatUnicodeText 350 // 退出 Word 351 //wordType.InvokeMember( "Quit", System.Reflection.BindingFlags.InvokeMethod, 352 // null, WordApp, null ); 353 #endregion 354 355 //保存 356 WordDoc.Save(); 357 WordDoc.Close(ref oMissing, ref oMissing, ref oMissing); 358 WordApp.Quit(ref oMissing, ref oMissing, ref oMissing); 359 return true; 360 } 361 catch (Exception e) 362 { 363 Console.WriteLine(e.Message); 364 Console.WriteLine(e.StackTrace); 365 return false; 366 } 367 } 368 #endregion 把Word文档转化为Html文件 369 370 #region word中添加新表 371 /// <summary> 372 /// word中添加新表 373 /// </summary> 374 public static void AddTable() 375 { 376 object oMissing = System.Reflection.Missing.Value; 377 Microsoft.Office.Interop.Word._Application WordApp; 378 Microsoft.Office.Interop.Word._Document WordDoc; 379 WordApp = new Microsoft.Office.Interop.Word.Application(); 380 WordApp.Visible = true; 381 WordDoc = WordApp.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing); 382 383 object start = 0; 384 object end = 0; 385 Microsoft.Office.Interop.Word.Range tableLocation = WordDoc.Range(ref start, ref end); 386 WordDoc.Tables.Add(tableLocation, 3, 4, ref oMissing, ref oMissing);//3行4列的表 387 } 388 #endregion word中添加新表 389 390 #region 在表中插入新行 391 392 /// <summary> 393 /// 在表中插入新的1行 394 /// </summary> 395 public static void AddRow() 396 { 397 object oMissing = System.Reflection.Missing.Value; 398 Microsoft.Office.Interop.Word._Application WordApp; 399 Microsoft.Office.Interop.Word._Document WordDoc; 400 WordApp = new Microsoft.Office.Interop.Word.Application(); 401 WordApp.Visible = true; 402 WordDoc = WordApp.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing); 403 404 object start = 0; 405 object end = 0; 406 Microsoft.Office.Interop.Word.Range tableLocation = WordDoc.Range(ref start, ref end); 407 WordDoc.Tables.Add(tableLocation, 3, 4, ref oMissing, ref oMissing); 408 409 Microsoft.Office.Interop.Word.Table newTable = WordDoc.Tables[1]; 410 object beforeRow = newTable.Rows[1]; 411 newTable.Rows.Add(ref beforeRow); 412 } 413 #endregion 414 415 #region 合并单元格 416 /// <summary> 417 /// 合并单元格 418 /// </summary> 419 public static void CombinationCell() 420 { 421 object oMissing = System.Reflection.Missing.Value; 422 Microsoft.Office.Interop.Word._Application WordApp; 423 Microsoft.Office.Interop.Word._Document WordDoc; 424 WordApp = new Microsoft.Office.Interop.Word.Application(); 425 WordApp.Visible = true; 426 WordDoc = WordApp.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing); 427 428 object start = 0; 429 object end = 0; 430 Microsoft.Office.Interop.Word.Range tableLocation = WordDoc.Range(ref start, ref end); 431 WordDoc.Tables.Add(tableLocation, 3, 4, ref oMissing, ref oMissing); 432 433 Microsoft.Office.Interop.Word.Table newTable = WordDoc.Tables[1]; 434 object beforeRow = newTable.Rows[1]; 435 newTable.Rows.Add(ref beforeRow); 436 437 Microsoft.Office.Interop.Word.Cell cell = newTable.Cell(2, 1);//2行1列合并2行2列为一起 438 cell.Merge(newTable.Cell(2, 2)); 439 //cell.Merge( newTable.Cell( 1, 3 ) ); 440 } 441 #endregion 合并单元格 442 443 #region 分离单元格 444 /// <summary> 445 /// 分离单元格 446 /// </summary> 447 public static void SeparateCell() 448 { 449 object oMissing = System.Reflection.Missing.Value; 450 Microsoft.Office.Interop.Word._Application WordApp; 451 Microsoft.Office.Interop.Word._Document WordDoc; 452 WordApp = new Microsoft.Office.Interop.Word.Application(); 453 WordApp.Visible = true; 454 WordDoc = WordApp.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing); 455 456 object start = 0; 457 object end = 0; 458 Microsoft.Office.Interop.Word.Range tableLocation = WordDoc.Range(ref start, ref end); 459 WordDoc.Tables.Add(tableLocation, 3, 4, ref oMissing, ref oMissing); 460 461 Microsoft.Office.Interop.Word.Table newTable = WordDoc.Tables[1]; 462 object beforeRow = newTable.Rows[1]; 463 newTable.Rows.Add(ref beforeRow); 464 465 Microsoft.Office.Interop.Word.Cell cell = newTable.Cell(1, 1); 466 cell.Merge(newTable.Cell(1, 2)); 467 468 object Rownum = 2; 469 object Columnnum = 2; 470 cell.Split(ref Rownum, ref Columnnum); 471 } 472 #endregion 分离单元格 473 474 #region 通过段落控制插入 475 /// <summary> 476 /// 通过段落控制插入Insert a paragraph at the beginning of the document. 477 /// </summary> 478 public static void InsertParagraph() 479 { 480 object oMissing = System.Reflection.Missing.Value; 481 //object oEndOfDoc = "\\endofdoc"; 482 //endofdoc is a predefined bookmark 483 484 //Start Word and create a new document. 485 Microsoft.Office.Interop.Word._Application WordApp; 486 Microsoft.Office.Interop.Word._Document WordDoc; 487 WordApp = new Microsoft.Office.Interop.Word.Application(); 488 WordApp.Visible = true; 489 490 WordDoc = WordApp.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing); 491 492 //Insert a paragraph at the beginning of the document. 493 Microsoft.Office.Interop.Word.Paragraph oPara1; 494 oPara1 = WordDoc.Content.Paragraphs.Add(ref oMissing); 495 oPara1.Range.Text = "Heading 1"; 496 oPara1.Range.Font.Bold = 1; 497 oPara1.Format.SpaceAfter = 24; //24 pt spacing after paragraph. 498 oPara1.Range.InsertParagraphAfter(); 499 } 500 #endregion 通过段落控制插入 501 502 #region word文档设置及获取光标位置 503 504 /// <summary> 505 /// word文档设置及获取光标位置 506 /// </summary> 507 public static void WordSet() 508 { 509 object oMissing = System.Reflection.Missing.Value; 510 Microsoft.Office.Interop.Word._Application WordApp; 511 WordApp = new Microsoft.Office.Interop.Word.Application(); 512 513 #region 文档格式设置 514 WordApp.ActiveDocument.PageSetup.LineNumbering.Active = 0;//行编号 515 WordApp.ActiveDocument.PageSetup.Orientation = Microsoft.Office.Interop.Word.WdOrientation.wdOrientPortrait;//页面方向 516 WordApp.ActiveDocument.PageSetup.TopMargin = WordApp.CentimetersToPoints(float.Parse("2.54"));//上页边距 517 WordApp.ActiveDocument.PageSetup.BottomMargin = WordApp.CentimetersToPoints(float.Parse("2.54"));//下页边距 518 WordApp.ActiveDocument.PageSetup.LeftMargin = WordApp.CentimetersToPoints(float.Parse("3.17"));//左页边距 519 WordApp.ActiveDocument.PageSetup.RightMargin = WordApp.CentimetersToPoints(float.Parse("3.17"));//右页边距 520 WordApp.ActiveDocument.PageSetup.Gutter = WordApp.CentimetersToPoints(float.Parse("0"));//装订线位置 521 WordApp.ActiveDocument.PageSetup.HeaderDistance = WordApp.CentimetersToPoints(float.Parse("1.5"));//页眉 522 WordApp.ActiveDocument.PageSetup.FooterDistance = WordApp.CentimetersToPoints(float.Parse("1.75"));//页脚 523 WordApp.ActiveDocument.PageSetup.PageWidth = WordApp.CentimetersToPoints(float.Parse("21"));//纸张宽度 524 WordApp.ActiveDocument.PageSetup.PageHeight = WordApp.CentimetersToPoints(float.Parse("29.7"));//纸张高度 525 WordApp.ActiveDocument.PageSetup.FirstPageTray = Microsoft.Office.Interop.Word.WdPaperTray.wdPrinterDefaultBin;//纸张来源 526 WordApp.ActiveDocument.PageSetup.OtherPagesTray = Microsoft.Office.Interop.Word.WdPaperTray.wdPrinterDefaultBin;//纸张来源 527 WordApp.ActiveDocument.PageSetup.SectionStart = Microsoft.Office.Interop.Word.WdSectionStart.wdSectionNewPage;//节的起始位置:新建页 528 WordApp.ActiveDocument.PageSetup.OddAndEvenPagesHeaderFooter = 0;//页眉页脚-奇偶页不同 529 WordApp.ActiveDocument.PageSetup.DifferentFirstPageHeaderFooter = 0;//页眉页脚-首页不同 530 WordApp.ActiveDocument.PageSetup.VerticalAlignment = Microsoft.Office.Interop.Word.WdVerticalAlignment.wdAlignVerticalTop;//页面垂直对齐方式 531 WordApp.ActiveDocument.PageSetup.SuppressEndnotes = 0;//不隐藏尾注 532 WordApp.ActiveDocument.PageSetup.MirrorMargins = 0;//不设置首页的内外边距 533 WordApp.ActiveDocument.PageSetup.TwoPagesOnOne = false;//不双面打印 534 WordApp.ActiveDocument.PageSetup.BookFoldPrinting = false;//不设置手动双面正面打印 535 WordApp.ActiveDocument.PageSetup.BookFoldRevPrinting = false;//不设置手动双面背面打印 536 WordApp.ActiveDocument.PageSetup.BookFoldPrintingSheets = 1;//打印默认份数 537 WordApp.ActiveDocument.PageSetup.GutterPos = Microsoft.Office.Interop.Word.WdGutterStyle.wdGutterPosLeft;//装订线位于左侧 538 WordApp.ActiveDocument.PageSetup.LinesPage = 40;//默认页行数量 539 WordApp.ActiveDocument.PageSetup.LayoutMode = Microsoft.Office.Interop.Word.WdLayoutMode.wdLayoutModeLineGrid;//版式模式为“只指定行网格” 540 #endregion 文档格式设置 541 542 #region 段落格式设定 543 WordApp.Selection.ParagraphFormat.LeftIndent = WordApp.CentimetersToPoints(float.Parse("0"));//左缩进 544 WordApp.Selection.ParagraphFormat.RightIndent = WordApp.CentimetersToPoints(float.Parse("0"));//右缩进 545 WordApp.Selection.ParagraphFormat.SpaceBefore = float.Parse("0");//段前间距 546 WordApp.Selection.ParagraphFormat.SpaceBeforeAuto = 0;// 547 WordApp.Selection.ParagraphFormat.SpaceAfter = float.Parse("0");//段后间距 548 WordApp.Selection.ParagraphFormat.SpaceAfterAuto = 0;// 549 WordApp.Selection.ParagraphFormat.LineSpacingRule = Microsoft.Office.Interop.Word.WdLineSpacing.wdLineSpaceSingle;//单倍行距 550 WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphJustify;//段落2端对齐 551 WordApp.Selection.ParagraphFormat.WidowControl = 0;//孤行控制 552 WordApp.Selection.ParagraphFormat.KeepWithNext = 0;//与下段同页 553 WordApp.Selection.ParagraphFormat.KeepTogether = 0;//段中不分页 554 WordApp.Selection.ParagraphFormat.PageBreakBefore = 0;//段前分页 555 WordApp.Selection.ParagraphFormat.NoLineNumber = 0;//取消行号 556 WordApp.Selection.ParagraphFormat.Hyphenation = 1;//取消段字 557 WordApp.Selection.ParagraphFormat.FirstLineIndent = WordApp.CentimetersToPoints(float.Parse("0"));//首行缩进 558 WordApp.Selection.ParagraphFormat.OutlineLevel = Microsoft.Office.Interop.Word.WdOutlineLevel.wdOutlineLevelBodyText; 559 WordApp.Selection.ParagraphFormat.CharacterUnitLeftIndent = float.Parse("0"); 560 WordApp.Selection.ParagraphFormat.CharacterUnitRightIndent = float.Parse("0"); 561 WordApp.Selection.ParagraphFormat.CharacterUnitFirstLineIndent = float.Parse("0"); 562 WordApp.Selection.ParagraphFormat.LineUnitBefore = float.Parse("0"); 563 WordApp.Selection.ParagraphFormat.LineUnitAfter = float.Parse("0"); 564 WordApp.Selection.ParagraphFormat.AutoAdjustRightIndent = 1; 565 WordApp.Selection.ParagraphFormat.DisableLineHeightGrid = 0; 566 WordApp.Selection.ParagraphFormat.FarEastLineBreakControl = 1; 567 WordApp.Selection.ParagraphFormat.WordWrap = 1; 568 WordApp.Selection.ParagraphFormat.HangingPunctuation = 1; 569 WordApp.Selection.ParagraphFormat.HalfWidthPunctuationOnTopOfLine = 0; 570 WordApp.Selection.ParagraphFormat.AddSpaceBetweenFarEastAndAlpha = 1; 571 WordApp.Selection.ParagraphFormat.AddSpaceBetweenFarEastAndDigit = 1; 572 WordApp.Selection.ParagraphFormat.BaseLineAlignment = Microsoft.Office.Interop.Word.WdBaselineAlignment.wdBaselineAlignAuto; 573 #endregion 段落格式设定 574 575 #region 字体格式设定 576 WordApp.Selection.Font.NameFarEast = "华文中宋"; 577 WordApp.Selection.Font.NameAscii = "Times New Roman"; 578 WordApp.Selection.Font.NameOther = "Times New Roman"; 579 WordApp.Selection.Font.Name = "宋体"; 580 WordApp.Selection.Font.Size = float.Parse("14"); 581 WordApp.Selection.Font.Bold = 0; 582 WordApp.Selection.Font.Italic = 0; 583 WordApp.Selection.Font.Underline = Microsoft.Office.Interop.Word.WdUnderline.wdUnderlineNone; 584 WordApp.Selection.Font.UnderlineColor = Microsoft.Office.Interop.Word.WdColor.wdColorAutomatic; 585 WordApp.Selection.Font.StrikeThrough = 0;//删除线 586 WordApp.Selection.Font.DoubleStrikeThrough = 0;//双删除线 587 WordApp.Selection.Font.Outline = 0;//空心 588 WordApp.Selection.Font.Emboss = 0;//阳文 589 WordApp.Selection.Font.Shadow = 0;//阴影 590 WordApp.Selection.Font.Hidden = 0;//隐藏文字 591 WordApp.Selection.Font.SmallCaps = 0;//小型大写字母 592 WordApp.Selection.Font.AllCaps = 0;//全部大写字母 593 WordApp.Selection.Font.Color = Microsoft.Office.Interop.Word.WdColor.wdColorAutomatic; 594 WordApp.Selection.Font.Engrave = 0;//阴文 595 WordApp.Selection.Font.Superscript = 0;//上标 596 WordApp.Selection.Font.Subscript = 0;//下标 597 WordApp.Selection.Font.Spacing = float.Parse("0");//字符间距 598 WordApp.Selection.Font.Scaling = 100;//字符缩放 599 WordApp.Selection.Font.Position = 0;//位置 600 WordApp.Selection.Font.Kerning = float.Parse("1");//字体间距调整 601 WordApp.Selection.Font.Animation = Microsoft.Office.Interop.Word.WdAnimation.wdAnimationNone;//文字效果 602 WordApp.Selection.Font.DisableCharacterSpaceGrid = false; 603 WordApp.Selection.Font.EmphasisMark = Microsoft.Office.Interop.Word.WdEmphasisMark.wdEmphasisMarkNone; 604 #endregion 字体格式设定 605 606 #region 获取光标位置 607 ////get_Information 608 WordApp.Selection.get_Information(WdInformation.wdActiveEndPageNumber); 609 //关于行号-页号-列号-位置 610 //information 属性 611 //返回有关指定的所选内容或区域的信息。variant 类型,只读。 612 //expression.information(type) 613 //expression 必需。该表达式返回一个 range 或 selection 对象。 614 //type long 类型,必需。需要返回的信息。可取下列 wdinformation 常量之一: 615 //wdactiveendadjustedpagenumber 返回页码,在该页中包含指定的所选内容或区域的活动结尾。如果设置了一个起始页码,并对页码进行了手工调整,则返回调整过的页码。 616 //wdactiveendpagenumber 返回页码,在该页中包含指定的所选内容或区域的活动结尾,页码从文档的开头开始计算而不考虑对页码的任何手工调整。 617 //wdactiveendsectionnumber 返回节号,在该节中包含了指定的所选内容或区域的活动结尾。 618 //wdatendofrowmarker 如果指定的所选内容或区域位于表格的行结尾标记处,则本参数返回 true。 619 //wdcapslock 如果大写字母锁定模式有效,则本参数返回 true。 620 //wdendofrangecolumnnumber 返回表格列号,在该表格列中包含了指定的所选内容或区域的活动结尾。 621 //wdendofrangerownumber 返回表格行号,在该表格行包含了指定的所选内容或区域的活动结尾。 622 //wdfirstcharactercolumnnumber 返回指定的所选内容或区域中第一个字符的位置。如果所选内容或区域是折叠的,则返回所选内容或区域右侧紧接着的字符编号。 623 //wdfirstcharacterlinenumber 返回所选内容中第一个字符的行号。如果 pagination 属性为 false,或 draft 属性为 true,则返回 - 1。 624 //wdframeisselected 如果所选内容或区域是一个完整的图文框文本框,则本参数返回 true。 625 //wdheaderfootertype 返回一个值,该值表明包含了指定的所选内容或区域的页眉或页脚的类型,如下表所示。 值 页眉或页脚的类型 626 //- 1 无 627 //0 偶数页页眉 628 //1 奇数页页眉 629 //2 偶数页页脚 630 //3 奇数页页脚 631 //4 第一个页眉 632 //5 第一个页脚 633 //wdhorizontalpositionrelativetopage 返回指定的所选内容或区域的水平位置。该位置是所选内容或区域的左边与页面的左边之间的距离,以磅为单位。如果所选内容或区域不可见,则返回 - 1。 634 //wdhorizontalpositionrelativetotextboundary 返回指定的所选内容或区域相对于周围最近的正文边界的左边的水平位置,以磅为单位。如果所选内容或区域没有显示在当前屏幕,则本参数返回 - 1。 635 //wdinclipboard 有关此常量的详细内容,请参阅 microsoft office 98 macintosh 版的语言参考帮助。 636 //wdincommentpane 如果指定的所选内容或区域位于批注窗格,则返回 true。 637 //wdinendnote 如果指定的所选内容或区域位于页面视图的尾注区内,或者位于普通视图的尾注窗格中,则本参数返回 true。 638 //wdinfootnote 如果指定的所选内容或区域位于页面视图的脚注区内,或者位于普通视图的脚注窗格中,则本参数返回 true。 639 //wdinfootnoteendnotepane 如果指定的所选内容或区域位于页面视图的脚注或尾注区内,或者位于普通视图的脚注或尾注窗格中,则本参数返回 true。详细内容,请参阅前面的 wdinfootnote 和 wdinendnote 的说明。 640 //wdinheaderfooter 如果指定的所选内容或区域位于页眉或页脚窗格中,或者位于页面视图的页眉或页脚中,则本参数返回 true。 641 //wdinmasterdocument 如果指定的所选内容或区域位于主控文档中,则本参数返回 true。 642 //wdinwordmail 返回一个值,该值表明了所选内容或区域的的位置,如下表所示。值 位置 643 //0 所选内容或区域不在一条电子邮件消息中。 644 //1 所选内容或区域位于正在发送的电子邮件中。 645 //2 所选内容或区域位于正在阅读的电子邮件中。 646 //wdmaximumnumberofcolumns 返回所选内容或区域中任何行的最大表格列数。 647 //wdmaximumnumberofrows 返回指定的所选内容或区域中表格的最大行数。 648 //wdnumberofpagesindocument 返回与所选内容或区域相关联的文档的页数。 649 //wdnumlock 如果 num lock 有效,则本参数返回 true。 650 //wdovertype 如果改写模式有效,则本参数返回 true。可用 overtype 属性改变改写模式的状态。 651 //wdreferenceoftype 返回一个值,该值表明所选内容相对于脚注、尾注或批注引用的位置,如下表所示。 值 描述 652 //— 1 所选内容或区域包含、但不只限定于脚注、尾注或批注引用中。 653 //0 所选内容或区域不在脚注、尾注或批注引用之前。 654 //1 所选内容或区域位于脚注引用之前。 655 //2 所选内容或区域位于尾注引用之前。 656 //3 所选内容或区域位于批注引用之前。 657 //wdrevisionmarking 如果修订功能处于活动状态,则本参数返回 true。 658 //wdselectionmode 返回一个值,该值表明当前的选定模式,如下表所示。 值 选定模式 659 //0 常规选定 660 //1 扩展选定 661 //2 列选定 662 //wdstartofrangecolumnnumber 返回所选内容或区域的起点所在的表格的列号。 663 //wdstartofrangerownumber 返回所选内容或区域的起点所在的表格的行号。 664 //wdverticalpositionrelativetopage 返回所选内容或区域的垂直位置,即所选内容的上边与页面的上边之间的距离,以磅为单位。如果所选内容或区域没有显示在屏幕上,则本参数返回 - 1。 665 //wdverticalpositionrelativetotextboundary 返回所选内容或区域相对于周围最近的正文边界的上边的垂直位置,以磅为单位。如果所选内容或区域没有显示在屏幕上,则本参数返回 - 1。 666 //wdwithintable 如果所选内容位于一个表格中,则本参数返回 true。 667 //wdzoompercentage 返回由 percentage 属性设置的当前的放大百分比。 668 #endregion 获取光标位置 669 670 #region 光标移动 671 //移动光标 672 //光标下移3行 上移3行 673 object unit = Microsoft.Office.Interop.Word.WdUnits.wdLine; 674 object count = 3; 675 WordApp.Selection.MoveEnd(ref unit, ref count); 676 WordApp.Selection.MoveUp(ref unit, ref count, ref oMissing); 677 678 //Microsoft.Office.Interop.Word.WdUnits说明 679 //wdCell A cell. 680 //wdCharacter A character. 681 //wdCharacterFormatting Character formatting. 682 //wdColumn A column. 683 //wdItem The selected item. 684 //wdLine A line. //行 685 //wdParagraph A paragraph. 686 //wdParagraphFormatting Paragraph formatting. 687 //wdRow A row. 688 //wdScreen The screen dimensions. 689 //wdSection A section. 690 //wdSentence A sentence. 691 //wdStory A story. 692 //wdTable A table. 693 //wdWindow A window. 694 //wdWord A word. 695 696 //录制的vb宏 697 // ,移动光标至当前行首 698 // Selection.HomeKey unit:=wdLine 699 // ‘移动光标至当前行尾 700 // Selection.EndKey unit:=wdLine 701 // ‘选择从光标至当前行首的内容 702 // Selection.HomeKey unit:=wdLine, Extend:=wdExtend 703 // ‘选择从光标至当前行尾的内容 704 // Selection.EndKey unit:=wdLine, Extend:=wdExtend 705 // ‘选择当前行 706 // Selection.HomeKey unit:=wdLine 707 // Selection.EndKey unit:=wdLine, Extend:=wdExtend 708 // ‘移动光标至文档开始 709 // Selection.HomeKey unit:=wdStory 710 // ‘移动光标至文档结尾 711 // Selection.EndKey unit:=wdStory 712 // ‘选择从光标至文档开始的内容 713 // Selection.HomeKey unit:=wdStory, Extend:=wdExtend 714 // ‘选择从光标至文档结尾的内容 715 // Selection.EndKey unit:=wdStory, Extend:=wdExtend 716 // ‘选择文档全部内容(从WholeStory可猜出Story应是当前文档的意思) 717 // Selection.WholeStory 718 // ‘移动光标至当前段落的开始 719 // Selection.MoveUp unit:=wdParagraph 720 // ‘移动光标至当前段落的结尾 721 // Selection.MoveDown unit:=wdParagraph 722 // ‘选择从光标至当前段落开始的内容 723 // Selection.MoveUp unit:=wdParagraph, Extend:=wdExtend 724 // ‘选择从光标至当前段落结尾的内容 725 // Selection.MoveDown unit:=wdParagraph, Extend:=wdExtend 726 // ‘选择光标所在段落的内容 727 // Selection.MoveUp unit:=wdParagraph 728 // Selection.MoveDown unit:=wdParagraph, Extend:=wdExtend 729 // ‘显示选择区的开始与结束的位置,注意:文档第1个字符的位置是0 730 // MsgBox ("第" & Selection.Start & "个字符至第" & Selection.End & "个字符") 731 // ‘删除当前行 732 // Selection.HomeKey unit:=wdLine 733 // Selection.EndKey unit:=wdLine, Extend:=wdExtend 734 // Selection.Delete 735 // ‘删除当前段落 736 // Selection.MoveUp unit:=wdParagraph 737 // Selection.MoveDown unit:=wdParagraph, Extend:=wdExtend 738 // Selection.Delete 739 740 741 //表格的光标移动 742 //光标到当前光标所在表格的地单元格 743 WordApp.Selection.Tables[1].Cell(1, 1).Select(); 744 //unit对象定义 745 object unith = Microsoft.Office.Interop.Word.WdUnits.wdRow;//表格行方式 746 object extend = Microsoft.Office.Interop.Word.WdMovementType.wdExtend;//extend对光标移动区域进行扩展选择 747 object unitu = Microsoft.Office.Interop.Word.WdUnits.wdLine;//文档行方式,可以看成表格一行.不过和wdRow有区别 748 object unitp = Microsoft.Office.Interop.Word.WdUnits.wdParagraph;//段落方式,对于表格可以选择到表格行后的换车符,对于跨行合并的行选择,我能找到的最简单方式 749 //object count = 1;//光标移动量 750 751 #endregion 光标移动 752 } 753 #endregion word文档设置及获取光标位置 754 755 #region 读取Word表格中某个单元格的数据。其中的参数分别为文件名(包括路径),行号,列号。 756 757 /// <summary> 758 /// 读取Word表格中某个单元格的数据。其中的参数分别为文件名(包括路径),行号,列号。 759 /// </summary> 760 /// <param name="fileName">word文档</param> 761 /// <param name="rowIndex">行</param> 762 /// <param name="colIndex">列</param> 763 /// <returns>返回数据</returns> 764 public static string ReadWord_tableContentByCell(string fileName, int rowIndex, int colIndex) 765 { 766 Microsoft.Office.Interop.Word._Application cls = null; 767 Microsoft.Office.Interop.Word._Document doc = null; 768 Microsoft.Office.Interop.Word.Table table = null; 769 object missing = System.Reflection.Missing.Value; 770 object path = fileName; 771 cls = new Application(); 772 try 773 { 774 doc = cls.Documents.Open 775 (ref path, ref missing, ref missing, ref missing, 776 ref missing, ref missing, ref missing, ref missing, 777 ref missing, ref missing, ref missing, ref missing, 778 ref missing, ref missing, ref missing, ref missing); 779 table = doc.Tables[1]; 780 string text = table.Cell(rowIndex, colIndex).Range.Text.ToString(); 781 text = text.Substring(0, text.Length - 2); //去除尾部的mark 782 return text; 783 } 784 catch (Exception ex) 785 { 786 return ex.Message; 787 } 788 finally 789 { 790 if (doc != null) 791 doc.Close(ref missing, ref missing, ref missing); 792 cls.Quit(ref missing, ref missing, ref missing); 793 } 794 } 795 #endregion 读取Word表格中某个单元格的数据。 796 797 #region 修改word表格中指定单元格的数据 798 /// <summary> 799 /// 修改word表格中指定单元格的数据 800 /// </summary> 801 /// <param name="fileName">word文档包括路径</param> 802 /// <param name="rowIndex">行</param> 803 /// <param name="colIndex">列</param> 804 /// <param name="content"></param> 805 /// <returns></returns> 806 public static bool UpdateWordTableByCell(string fileName, int rowIndex, int colIndex, string content) 807 { 808 Microsoft.Office.Interop.Word._Application cls = null; 809 Microsoft.Office.Interop.Word._Document doc = null; 810 Microsoft.Office.Interop.Word.Table table = null; 811 object missing = System.Reflection.Missing.Value; 812 object path = fileName; 813 cls = new Application(); 814 try 815 { 816 doc = cls.Documents.Open 817 (ref path, ref missing, ref missing, ref missing, 818 ref missing, ref missing, ref missing, ref missing, 819 ref missing, ref missing, ref missing, ref missing, 820 ref missing, ref missing, ref missing, ref missing); 821 822 table = doc.Tables[1]; 823 //doc.Range( ref 0, ref 0 ).InsertParagraphAfter();//插入回车 824 table.Cell(rowIndex, colIndex).Range.InsertParagraphAfter();//.Text = content; 825 return true; 826 } 827 catch 828 { 829 return false; 830 } 831 finally 832 { 833 if (doc != null) 834 { 835 doc.Close(ref missing, ref missing, ref missing); 836 cls.Quit(ref missing, ref missing, ref missing); 837 } 838 } 839 } 840 #endregion 841 842 #region 关闭word进程 843 /// <summary> 844 /// 关闭word进程 845 /// </summary> 846 public static void KillWordProcess() 847 { 848 System.Diagnostics.Process[] myProcess; 849 myProcess = System.Diagnostics.Process.GetProcesses(); 850 foreach (System.Diagnostics.Process process in myProcess) 851 { 852 if (process.Id != 0) 853 { 854 string myS = "WINWORD.EXE" + process.ProcessName + " ID:" + process.Id.ToString(); 855 try 856 { 857 if (process.Modules != null) 858 if (process.Modules.Count > 0) 859 { 860 System.Diagnostics.ProcessModule pm = process.Modules[0]; 861 myS += "\n Modules[0].FileName:" + pm.FileName; 862 myS += "\n Modules[0].ModuleName:" + pm.ModuleName; 863 myS += "\n Modules[0].FileVersionInfo:\n" + pm.FileVersionInfo.ToString(); 864 if (pm.ModuleName.ToLower() == "winword.exe") 865 process.Kill(); 866 } 867 } 868 catch 869 { } 870 finally 871 { 872 } 873 } 874 } 875 } 876 #endregion 关闭word进程 877 878 #region 判断系统是否装word 879 880 /// <summary> 881 /// 判断系统是否装word 882 /// </summary> 883 /// <returns></returns> 884 public static bool IsWordInstalled() 885 { 886 RegistryKey machineKey = Registry.LocalMachine; 887 if (IsWordInstalledByVersion("12.0", machineKey)) 888 { 889 return true; 890 } 891 if (IsWordInstalledByVersion("11.0", machineKey)) 892 { 893 return true; 894 } 895 return false; 896 } 897 898 899 /// <summary> 900 /// 判断系统是否装某版本的word 901 /// </summary> 902 /// <param name="strVersion">版本号</param> 903 /// <param name="machineKey"></param> 904 /// <returns></returns> 905 private static bool IsWordInstalledByVersion(string strVersion, RegistryKey machineKey) 906 { 907 try 908 { 909 RegistryKey installKey = 910 machineKey.OpenSubKey("Software").OpenSubKey("Microsoft").OpenSubKey( 911 "Office").OpenSubKey(strVersion).OpenSubKey("Word").OpenSubKey("InstallRoot"); 912 if (installKey == null) 913 { 914 return false; 915 } 916 return true; 917 } 918 catch(Exception e) 919 { 920 Console.WriteLine(e.Message); 921 Console.WriteLine(e.StackTrace); 922 return false; 923 } 924 } 925 #endregion 判断系统是否装word 926 }
原文:http://www.cnblogs.com/endv/p/5199649.html