C#操作Word的辅助类(word2003) 修改完善版

转自:http://blog.csdn.net/jiutao_tang/article/details/6567608

该类在他人编写的几个类基础上扩展完善而来,主要功能有:

(1)插入文本

(2)插入图片

(3)插入表格

(4)载入模版

(5)编辑模版,利用标签等

(6)插入页眉页脚

   1 /***************************************************************************
   2  * word辅助类
   3  * 作者:chengfellow
   4  * 日期:2008.8.18
   5  * 注意事项:
   6  * 1、开发环境居于office 2003;
   7  * 2、需要添加Com引用:Microsoft Office 11.0 Object Library和
   8  *    Microsoft Word 11.0 Object Library。
   9  * 
  10  
  11 ****************************************************************************/
  12 
  13 using
  14  System;
  15 using System.Collections.Generic;
  16 using System.Text;
  17 using System.Drawing;
  18 using System.Windows.Forms;
  19 using System.IO;
  20 using System.Data;
  21 namespace WordAddinSample
  22 {
  23     public class WordHelp
  24     {
  25         #region - 属性 -
  26         private Microsoft.Office.Interop.Word.ApplicationClass oWord;   
  27  // a reference to Word application,应用程序
  28         private Microsoft.Office.Interop.Word.Document oDoc;            
  29         // a reference to the document,具体文档
  30         object missing = System.Reflection.Missing.Value;
  31         public Microsoft.Office.Interop.Word.ApplicationClass 
  32 WordApplication
  33         {
  34             get { return oWord; }
  35         }
  36         public string ActiveWindowCaption {
  37             get {
  38                 return oWord.ActiveWindow.Caption;
  39             }
  40             set {
  41                 oWord.ActiveWindow.Caption = value;
  42             }
  43         }
  44         public enum OwdWrapType
  45         {
  46             嵌入型, //wdWrapInline
  47             四周型, //Square.
  48             紧密型, //Tight.
  49             衬于文字下方,//Behind text.
  50             衬于文字上方 //Top and bottom.
  51         }
  52         #endregion
  53         #region  - 创建关闭文档 -
  54         public WordHelp() //构造函数 1
  55         {
  56             // activate the interface with the COM object of Microsoft 
  57 Word
  58             oWord = new 
  59 Microsoft.Office.Interop.Word.ApplicationClass();
  60         }
  61         public WordHelp(Microsoft.Office.Interop.Word.ApplicationClass 
  62 wordapp) //构造函数 2
  63         {
  64             oWord = wordapp;
  65         }
  66         // Open a file (the file must exists) and activate it,打开已存在
  67         public void Open(string strFileName)
  68         {
  69             object fileName = strFileName;
  70             object readOnly = false;
  71             object isVisible = true;
  72             oDoc = oWord.Documents.Open(ref fileName, ref missing, ref 
  73 readOnly,
  74                 ref missing, ref missing, ref missing, ref missing, ref 
  75 missing, ref missing,
  76                 ref missing, ref missing, ref isVisible, ref missing, 
  77 ref missing, ref missing, ref missing);
  78             oDoc.Activate();
  79         }
  80         // Open a new document,创建新文档
  81         public void Open()
  82         {
  83             oDoc = oWord.Documents.Add(ref missing, ref missing, ref 
  84 missing, ref missing);
  85             oDoc.Activate();
  86         }
  87         public void Quit()
  88         {
  89             oDoc.Close(ref missing, ref missing, ref missing);
  90             if (oDoc != null)
  91             {
  92                 
  93 System.Runtime.InteropServices.Marshal.ReleaseComObject(oDoc);
  94                 oDoc = null;
  95             }
  96            // oWord.Application.Quit(ref missing, ref missing, ref 
  97 missing); tjt
  98             oWord.Quit(ref missing, ref missing, ref missing);
  99             if (oWord != null)
 100             {
 101                 
 102 System.Runtime.InteropServices.Marshal.ReleaseComObject(oWord);
 103                 oWord = null;
 104             }
 105             //释放word进程
 106             GC.Collect();
 107         }       
 108         /// <summary>  
 109         /// 从模板创建新的Word文档,  
 110         /// </summary>  
 111         /// <param name="templateName">模板文件名</param>  
 112         /// <returns></returns>  
 113         public bool LoadDotFile(string templateName)
 114         {
 115             if (!string.IsNullOrEmpty(templateName))
 116             {
 117                 oWord.Visible = false;
 118                 oWord.Caption = "";
 119                 oWord.Options.CheckSpellingAsYouType = false;
 120                 oWord.Options.CheckGrammarAsYouType = false;
 121                 Object Template = templateName;// Optional Object. The 
 122 name of the template to be used for the new document. If this argument 
 123 is omitted, the Normal template is used.  
 124                 Object NewTemplate = false;// Optional Object. True to 
 125 open the document as a template. The default value is False.  
 126                 Object DocumentType = 
 127 Microsoft.Office.Interop.Word.WdNewDocumentType.wdNewBlankDocument; // 
 128 Optional Object. Can be one of the following WdNewDocumentType 
 129 constants: wdNewBlankDocument, wdNewEmailMessage, wdNewFrameset, or 
 130 wdNewWebPage. The default constant is wdNewBlankDocument.  
 131                 Object Visible = true;//Optional Object. True to open 
 132 the document in a visible window. If this value is False, Microsoft Word
 133  opens the document but sets the Visible property of the document window
 134  to False. The default value is True.  
 135                 try
 136                 {
 137                     oDoc = oWord.Documents.Add(ref Template, ref 
 138 NewTemplate, ref DocumentType, ref Visible);
 139                     return true;
 140                 }
 141                 catch (Exception ex)
 142                 {
 143                     string err = string.Format("创建Word文档出错,错误原因:{0}", 
 144 ex.Message);
 145                     throw new Exception(err, ex);
 146                 }               
 147             }
 148             return false;
 149         }
 150         ///  
 151         /// 打开Word文档,并且返回对象oDoc
 152         /// 完整Word文件路径+名称  
 153         /// 返回的Word.Document oDoc对象 
 154         public Microsoft.Office.Interop.Word.Document 
 155 CreateWordDocument(string FileName, bool HideWin)
 156         {
 157             if (FileName == "") return null;
 158             oWord.Visible = HideWin;
 159             oWord.Caption = "";
 160             oWord.Options.CheckSpellingAsYouType = false;
 161             oWord.Options.CheckGrammarAsYouType = false;
 162             Object filename = FileName;
 163             Object ConfirmConversions = false;
 164             Object ReadOnly = true;
 165             Object AddToRecentFiles = false;
 166             Object PasswordDocument = System.Type.Missing;
 167             Object PasswordTemplate = System.Type.Missing;
 168             Object Revert = System.Type.Missing;
 169             Object WritePasswordDocument = System.Type.Missing;
 170             Object WritePasswordTemplate = System.Type.Missing;
 171             Object Format = System.Type.Missing;
 172             Object Encoding = System.Type.Missing;
 173             Object Visible = System.Type.Missing;
 174             Object OpenAndRepair = System.Type.Missing;
 175             Object DocumentDirection = System.Type.Missing;
 176             Object NoEncodingDialog = System.Type.Missing;
 177             Object XMLTransform = System.Type.Missing;
 178             try
 179             {
 180                 Microsoft.Office.Interop.Word.Document wordDoc = 
 181 oWord.Documents.Open(ref filename, ref ConfirmConversions,
 182                 ref ReadOnly, ref AddToRecentFiles, ref 
 183 PasswordDocument, ref PasswordTemplate,
 184                 ref Revert, ref WritePasswordDocument, ref 
 185 WritePasswordTemplate, ref Format,
 186                 ref Encoding, ref Visible, ref OpenAndRepair, ref 
 187 DocumentDirection,
 188                 ref NoEncodingDialog, ref XMLTransform);
 189                 return wordDoc;
 190             }
 191             catch (Exception ex)
 192             {
 193                 MessageBox.Show(ex.Message);
 194                 return null;
 195             }
 196         }
 197         public void SaveAs(Microsoft.Office.Interop.Word.Document oDoc, 
 198 string strFileName)
 199         {
 200             object fileName = strFileName;
 201             if (File.Exists(strFileName))
 202             {
 203                 if (MessageBox.Show("文件'" + strFileName + 
 204 "'已经存在,选确定覆盖原文件,选取消退出操作!", "警告", MessageBoxButtons.OKCancel) == 
 205 DialogResult.OK)
 206                 {
 207                     oDoc.SaveAs(ref fileName, ref missing, ref missing, 
 208 ref missing, ref missing, ref missing, ref missing,
 209                               ref missing, ref missing, ref missing, ref
 210  missing, ref missing, ref missing, ref missing, ref missing, ref 
 211 missing);
 212                 }
 213                 else
 214                 {
 215                     Clipboard.Clear();
 216                 }
 217             }
 218             else
 219             {
 220                 oDoc.SaveAs(ref fileName, ref missing, ref missing, ref 
 221 missing, ref missing, ref missing, ref missing,
 222                         ref missing, ref missing, ref missing, ref 
 223 missing, ref missing, ref missing, ref missing, ref missing, ref 
 224 missing);
 225             }
 226         }
 227         public void SaveAsHtml(Microsoft.Office.Interop.Word.Document 
 228 oDoc, string strFileName)
 229         {
 230             object fileName = strFileName;
 231             //wdFormatWebArchive保存为单个网页文件
 232             //wdFormatFilteredHTML保存为过滤掉word标签的htm文件,缺点是有图片的话会产生网页文件夹
 233             if (File.Exists(strFileName))
 234             {
 235                 if (MessageBox.Show("文件'" + strFileName + 
 236 "'已经存在,选确定覆盖原文件,选取消退出操作!", "警告", MessageBoxButtons.OKCancel) == 
 237 DialogResult.OK)
 238                 {
 239                     object Format = 
 240 (int)Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatWebArchive;
 241                     oDoc.SaveAs(ref fileName, ref Format, ref missing, 
 242 ref missing, ref missing, ref missing, ref missing,
 243                         ref missing, ref missing, ref missing, ref 
 244 missing, ref missing, ref missing, ref missing, ref missing, ref 
 245 missing);
 246                 }
 247                 else
 248                 {
 249                     Clipboard.Clear();
 250                 }
 251             }
 252             else
 253             {
 254                 object Format = 
 255 (int)Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatWebArchive;
 256                 oDoc.SaveAs(ref fileName, ref Format, ref missing, ref 
 257 missing, ref missing, ref missing, ref missing,
 258                     ref missing, ref missing, ref missing, ref missing, 
 259 ref missing, ref missing, ref missing, ref missing, ref missing);
 260             }
 261         }
 262         public void Save()
 263         {
 264             oDoc.Save();
 265         }
 266         public void SaveAs(string strFileName)
 267         {
 268             object fileName = strFileName;
 269             oDoc.SaveAs(ref fileName, ref missing, ref missing, ref 
 270 missing, ref missing, ref missing, ref missing,
 271                 ref missing, ref missing, ref missing, ref missing, ref 
 272 missing, ref missing, ref missing, ref missing, ref missing);
 273         }
 274         // Save the document in HTML format
 275         public void SaveAsHtml(string strFileName)
 276         {
 277             object fileName = strFileName;
 278             object Format = 
 279 (int)Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatHTML;
 280             oDoc.SaveAs(ref fileName, ref Format, ref missing, ref 
 281 missing, ref missing, ref missing, ref missing,
 282                 ref missing, ref missing, ref missing, ref missing, ref 
 283 missing, ref missing, ref missing, ref missing, ref missing);
 284         }
 285         #endregion
 286         #region 添加菜单(工具栏)项
 287         //添加单独的菜单项
 288         public void AddMenu(Microsoft.Office.Core.CommandBarPopup 
 289 popuBar)
 290         {
 291             Microsoft.Office.Core.CommandBar menuBar = null;
 292             menuBar = this.oWord.CommandBars["Menu Bar"];
 293             popuBar = 
 294 (Microsoft.Office.Core.CommandBarPopup)this.oWord.CommandBars.FindControl(Microsoft.Office.Core.MsoControlType.msoControlPopup,
 295  missing, popuBar.Tag, true);
 296             if (popuBar == null)
 297             {
 298                 popuBar = 
 299 (Microsoft.Office.Core.CommandBarPopup)menuBar.Controls.Add(Microsoft.Office.Core.MsoControlType.msoControlPopup,
 300  missing, missing, missing, missing);
 301             }
 302         }
 303         //添加单独工具栏
 304         public void AddToolItem(string strBarName, string strBtnName)
 305         {
 306             Microsoft.Office.Core.CommandBar toolBar = null;
 307             toolBar = 
 308 (Microsoft.Office.Core.CommandBar)this.oWord.CommandBars.FindControl(Microsoft.Office.Core.MsoControlType.msoControlButton,
 309  missing, strBarName, true);
 310             if (toolBar == null)
 311             {
 312                 toolBar = 
 313 (Microsoft.Office.Core.CommandBar)this.oWord.CommandBars.Add(
 314                      
 315 Microsoft.Office.Core.MsoControlType.msoControlButton,
 316                      missing, missing, missing);
 317                 toolBar.Name = strBtnName;
 318                 toolBar.Visible = true;
 319             }
 320         }
 321         #endregion
 322         #region 移动光标位置
 323         // Go to a predefined bookmark, if the bookmark doesn't exists 
 324 the application will raise an error
 325         public void GotoBookMark(string strBookMarkName)
 326         {
 327             // VB :  Selection.GoTo What:=wdGoToBookmark, Name:="nome"
 328             object Bookmark = 
 329 (int)Microsoft.Office.Interop.Word.WdGoToItem.wdGoToBookmark;
 330             object NameBookMark = strBookMarkName;
 331             oWord.Selection.GoTo(ref Bookmark, ref missing, ref missing,
 332  ref NameBookMark);
 333         }
 334         public void GoToTheEnd()
 335         {
 336             // VB :  Selection.EndKey Unit:=wdStory
 337             object unit;
 338             unit = Microsoft.Office.Interop.Word.WdUnits.wdStory;
 339             oWord.Selection.EndKey(ref unit, ref missing);
 340         }
 341         public void GoToLineEnd()
 342         {
 343             object unit = Microsoft.Office.Interop.Word.WdUnits.wdLine;
 344             object ext = 
 345 Microsoft.Office.Interop.Word.WdMovementType.wdExtend;
 346             oWord.Selection.EndKey(ref unit, ref ext);
 347         }
 348         public void GoToTheBeginning()
 349         {
 350             // VB : Selection.HomeKey Unit:=wdStory
 351             object unit;
 352             unit = Microsoft.Office.Interop.Word.WdUnits.wdStory;
 353             oWord.Selection.HomeKey(ref unit, ref missing);
 354         }
 355         public void GoToTheTable(int ntable)
 356         {
 357             //    Selection.GoTo What:=wdGoToTable, Which:=wdGoToFirst, 
 358 Count:=1, Name:=""
 359             //    Selection.Find.ClearFormatting
 360             //    With Selection.Find
 361             //        .Text = ""
 362             //        .Replacement.Text = ""
 363             //        .Forward = True
 364             //        .Wrap = wdFindContinue
 365             //        .Format = False
 366             //        .MatchCase = False
 367             //        .MatchWholeWord = False
 368             //        .MatchWildcards = False
 369             //        .MatchSoundsLike = False
 370             //        .MatchAllWordForms = False
 371             //    End With
 372             object what;
 373             what = Microsoft.Office.Interop.Word.WdUnits.wdTable;
 374             object which;
 375             which = 
 376 Microsoft.Office.Interop.Word.WdGoToDirection.wdGoToFirst;
 377             object count;
 378             count = 1;
 379             oWord.Selection.GoTo(ref what, ref which, ref count, ref 
 380 missing);
 381             oWord.Selection.Find.ClearFormatting();
 382             oWord.Selection.Text = "";
 383         }
 384         public void GoToRightCell()
 385         {
 386             // Selection.MoveRight Unit:=wdCell
 387             object direction;
 388             direction = Microsoft.Office.Interop.Word.WdUnits.wdCell;
 389             oWord.Selection.MoveRight(ref direction, ref missing, ref 
 390 missing);
 391         }
 392         public void GoToLeftCell()
 393         {
 394             // Selection.MoveRight Unit:=wdCell
 395             object direction;
 396             direction = Microsoft.Office.Interop.Word.WdUnits.wdCell;
 397             oWord.Selection.MoveLeft(ref direction, ref missing, ref 
 398 missing);
 399         }
 400         public void GoToDownCell()
 401         {
 402             // Selection.MoveRight Unit:=wdCell
 403             object direction;
 404             direction = Microsoft.Office.Interop.Word.WdUnits.wdLine;
 405             oWord.Selection.MoveDown(ref direction, ref missing, ref 
 406 missing);
 407         }
 408         public void GoToUpCell()
 409         {
 410             // Selection.MoveRight Unit:=wdCell
 411             object direction;
 412             direction = Microsoft.Office.Interop.Word.WdUnits.wdLine;
 413             oWord.Selection.MoveUp(ref direction, ref missing, ref 
 414 missing);
 415         }
 416         #endregion
 417         #region  - 插入操作  -
 418         public void InsertText(string strText) //插入文本
 419         {
 420             oWord.Selection.TypeText(strText);
 421         }
 422         public void InsertLineBreak() //插入换行符
 423         {
 424             oWord.Selection.TypeParagraph();
 425         }        
 426         /// <summary>
 427         /// 插入多个空行
 428         /// </summary>
 429         /// <param name="nline"></param>
 430         public void InsertLineBreak(int nline)
 431         {
 432             for (int i = 0; i < nline; i++)
 433                 oWord.Selection.TypeParagraph();
 434         }
 435         public void InsertPagebreak() //插入分页符
 436         {
 437             // VB : Selection.InsertBreak Type:=wdPageBreak
 438             object pBreak = 
 439 (int)Microsoft.Office.Interop.Word.WdBreakType.wdPageBreak;
 440             oWord.Selection.InsertBreak(ref pBreak);
 441         }
 442         // 插入页码
 443         public void InsertPageNumber() //在正文中插入页码
 444         {
 445             object wdFieldPage = 
 446 Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage;
 447             object preserveFormatting = true;
 448             oWord.Selection.Fields.Add(oWord.Selection.Range, ref 
 449 wdFieldPage, ref missing, ref preserveFormatting);
 450         }
 451         // 插入页码
 452         public void InsertPageNumber(string strAlign)
 453         {
 454             object wdFieldPage = 
 455 Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage;
 456             object preserveFormatting = true;
 457             oWord.Selection.Fields.Add(oWord.Selection.Range, ref 
 458 wdFieldPage, ref missing, ref preserveFormatting);
 459             SetAlignment(strAlign);
 460         }
 461         #region - 插入页脚 -
 462         public bool InsertPageFooter(string text)
 463         {
 464             try
 465             {
 466                 oWord.ActiveWindow.View.SeekView = 
 467 Microsoft.Office.Interop.Word.WdSeekView.wdSeekCurrentPageFooter;//页脚 
 468                 oWord.Selection.InsertAfter(text); //.InsertAfter(text);
 469  
 470                 return true;
 471             }
 472             catch (Exception)
 473             {
 474                 return false;
 475             }
 476         }
 477         public bool InsertPageHeader(string text)
 478         {
 479             try
 480             {
 481                 oWord.ActiveWindow.View.SeekView = 
 482 Microsoft.Office.Interop.Word.WdSeekView.wdSeekCurrentPageHeader;//页眉
 483                 oWord.Selection.InsertAfter(text); 
 484                 return true;
 485             }
 486             catch (Exception)
 487             {
 488                 return false;
 489             }
 490         }
 491         public bool InsertPageFooterNumber()
 492         {
 493             try
 494             {
 495                 oWord.ActiveWindow.View.SeekView = 
 496 Microsoft.Office.Interop.Word.WdSeekView.wdSeekCurrentPageHeader; //页眉
 497                 oWord.Selection.WholeStory();
 498                 
 499 oWord.Selection.ParagraphFormat.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].LineStyle
 500  = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleNone; //取消页眉的下划线
 501                 oWord.ActiveWindow.View.SeekView = 
 502 Microsoft.Office.Interop.Word.WdSeekView.wdSeekMainDocument; //转到正文
 503                 oWord.ActiveWindow.View.SeekView = 
 504 Microsoft.Office.Interop.Word.WdSeekView.wdSeekCurrentPageFooter;//页脚 
 505                 oWord.Selection.TypeText("");
 506                 object page = 
 507 Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage; //当前页码
 508                 oWord.Selection.Fields.Add(oWord.Selection.Range, ref 
 509 page, ref missing, ref missing);
 510                 oWord.Selection.TypeText("页/共");
 511                 object pages = 
 512 Microsoft.Office.Interop.Word.WdFieldType.wdFieldNumPages; //总页码
 513                 oWord.Selection.Fields.Add(oWord.Selection.Range, ref 
 514 pages, ref missing, ref missing);
 515                 oWord.Selection.TypeText("");
 516                 oWord.ActiveWindow.View.SeekView = 
 517 Microsoft.Office.Interop.Word.WdSeekView.wdSeekMainDocument;
 518                 return true;
 519             }
 520             catch (Exception)
 521             {
 522                 return false;
 523             }
 524         }
 525         #endregion
 526         public void InsertLine(float left, float top, float width, float
 527  weight, int r, int g, int b)
 528         {
 529             //SetFontColor("red");
 530             //SetAlignment("Center");
 531             object Anchor = oWord.Selection.Range;
 532             //int pLeft = 0, pTop = 0, pWidth = 0, pHeight = 0;
 533             //oWord.ActiveWindow.GetPoint(out pLeft, out pTop, out 
 534 pWidth, out pHeight,missing);
 535             //MessageBox.Show(pLeft + "," + pTop + "," + pWidth + "," + 
 536 pHeight);
 537             object rep = false;
 538             //left += oWord.ActiveDocument.PageSetup.LeftMargin;
 539             left = oWord.CentimetersToPoints(left);
 540             top = oWord.CentimetersToPoints(top);
 541             width = oWord.CentimetersToPoints(width);
 542             Microsoft.Office.Interop.Word.Shape s = 
 543 oWord.ActiveDocument.Shapes.AddLine(0, top, width, top, ref Anchor);
 544             s.Line.ForeColor.RGB = RGB(r, g, b);
 545             s.Line.Visible = Microsoft.Office.Core.MsoTriState.msoTrue;
 546             s.Line.Style = 
 547 Microsoft.Office.Core.MsoLineStyle.msoLineSingle;
 548             s.Line.Weight = weight;
 549         }
 550         #endregion
 551         #region - 插入图片 -
 552         public void InsertImage(string strPicPath, float picWidth, float
 553  picHeight)
 554         {
 555             string FileName = strPicPath;
 556             object LinkToFile = false;
 557             object SaveWithDocument = true;
 558             object Anchor = oWord.Selection.Range;
 559             oWord.ActiveDocument.InlineShapes.AddPicture(FileName, ref 
 560 LinkToFile, ref SaveWithDocument, ref Anchor).Select();
 561             oWord.Selection.InlineShapes[1].Width = picWidth; // 图片宽度 
 562             oWord.Selection.InlineShapes[1].Height = picHeight; // 图片高度
 563         }
 564         //public void InsertImage(string strPicPath, float picWidth, 
 565 float picHeight, OwdWrapType owdWrapType)
 566         //{
 567         //    string FileName = strPicPath;
 568         //    object LinkToFile = false;
 569         //    object SaveWithDocument = true;
 570         //    object Anchor = oWord.Selection.Range;
 571         //    oWord.ActiveDocument.InlineShapes.AddPicture(FileName, ref
 572  LinkToFile, ref SaveWithDocument, ref Anchor).Select();
 573         //    oWord.Selection.InlineShapes[1].Width = picWidth; // 图片宽度 
 574         //    oWord.Selection.InlineShapes[1].Height = picHeight; // 
 575 图片高度
 576         //    // 将图片设置为四面环绕型 
 577         //  //  Microsoft.Office.Interop.Word.Shape s = 
 578 oWord.Selection.InlineShapes[1].ConvertToShape();
 579         //  //  s.WrapFormat.Type = 
 580 Microsoft.Office.Interop.Word.WdWrapType.wdWrapNone; //wdWrapSquare 
 581 四周环绕型
 582         //}
 583         #endregion
 584         #region - 插入表格 -
 585         public bool InsertTable(DataTable dt, bool haveBorder, double[] 
 586 colWidths)
 587         {
 588             try
 589             {
 590                 object Nothing = System.Reflection.Missing.Value;
 591                 int lenght = oDoc.Characters.Count - 1;
 592                 object start = lenght;
 593                 object end = lenght;
 594                 //表格起始坐标
 595                 Microsoft.Office.Interop.Word.Range tableLocation = 
 596 oDoc.Range(ref start, ref end);
 597                 //添加Word表格     
 598                 Microsoft.Office.Interop.Word.Table table = 
 599 oDoc.Tables.Add(tableLocation, dt.Rows.Count, dt.Columns.Count, ref 
 600 Nothing, ref Nothing);
 601                 if (colWidths != null)
 602                 {
 603                     for (int i = 0; i < colWidths.Length; i++)
 604                     {
 605                         table.Columns[i + 1].Width = (float)(28.5F * 
 606 colWidths[i]);
 607                     }
 608                 }
 609                 ///设置TABLE的样式
 610                 table.Rows.HeightRule = 
 611 Microsoft.Office.Interop.Word.WdRowHeightRule.wdRowHeightAtLeast;
 612                 table.Rows.Height = 
 613 oWord.CentimetersToPoints(float.Parse("0.8"));
 614                 table.Range.Font.Size = 10.5F;
 615                 table.Range.Font.Name = "宋体";
 616                 table.Range.Font.Bold = 0;
 617                 table.Range.ParagraphFormat.Alignment = 
 618 Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
 619                 table.Range.Cells.VerticalAlignment = 
 620 Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
 621 
 622                 if (haveBorder == true)
 623                 {
 624                     //设置外框样式
 625                     table.Borders.OutsideLineStyle = 
 626 Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
 627                     table.Borders.InsideLineStyle = 
 628 Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
 629                     //样式设置结束
 630                 }
 631                 for (int row = 0; row < dt.Rows.Count; row++)
 632                 {
 633                     for (int col = 0; col < dt.Columns.Count; col++)
 634                     {
 635                         table.Cell(row + 1, col + 1).Range.Text = 
 636 dt.Rows[row][col].ToString();
 637                     }
 638                 }
 639                 return true;
 640             }
 641             catch (Exception e)
 642             {
 643                 MessageBox.Show(e.ToString(), "错误提示", 
 644 MessageBoxButtons.OK, MessageBoxIcon.Error);
 645                 return false;
 646             }
 647             finally
 648             {
 649             }
 650         }
 651         public bool InsertTable(DataTable dt, bool haveBorder)
 652         {
 653             return InsertTable(dt, haveBorder, null);
 654         }
 655         public bool InsertTable(DataTable dt)
 656         {
 657             return InsertTable(dt, false, null);
 658         }
 659         //插入表格结束
 660         #endregion 
 661         #region 设置样式
 662         /// <summary>
 663         /// Change the paragraph alignement
 664         /// </summary>
 665         /// <param name="strType"></param>
 666         public void SetAlignment(string strType)
 667         {
 668             switch (strType.ToLower())
 669             {
 670                 case "center":
 671                     oWord.Selection.ParagraphFormat.Alignment = 
 672 Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;
 673                     break;
 674                 case "left":
 675                     oWord.Selection.ParagraphFormat.Alignment = 
 676 Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft;
 677                     break;
 678                 case "right":
 679                     oWord.Selection.ParagraphFormat.Alignment = 
 680 Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight;
 681                     break;
 682                 case "justify":
 683                     oWord.Selection.ParagraphFormat.Alignment = 
 684 Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphJustify;
 685                     break;
 686             }
 687         }
 688 
 689         // if you use thif function to change the font you should call 
 690 it again with 
 691         // no parameter in order to set the font without a particular 
 692 format
 693         public void SetFont(string strType)
 694         {
 695             switch (strType)
 696             {
 697                 case "Bold":
 698                     oWord.Selection.Font.Bold = 1;
 699                     break;
 700                 case "Italic":
 701                     oWord.Selection.Font.Italic = 1;
 702                     break;
 703                 case "Underlined":
 704                     oWord.Selection.Font.Subscript = 0;
 705                     break;
 706             }
 707         }
 708         // disable all the style 
 709         public void SetFont()
 710         {
 711             oWord.Selection.Font.Bold = 0;
 712             oWord.Selection.Font.Italic = 0;
 713             oWord.Selection.Font.Subscript = 0;
 714             SetFontName("宋体"); //默认宋体,tjt
 715             SetFontSize(10.5f);  //默认五号字体,tjt
 716         }
 717         public void SetFontName(string strType)
 718         {
 719             oWord.Selection.Font.Name = strType;
 720         }
 721         public void SetFontSize(float nSize)
 722         {
 723             SetFontSize(nSize, 100);
 724         }
 725         public void SetFontSize(float nSize, int scaling)
 726         {
 727             if (nSize > 0f)
 728                 oWord.Selection.Font.Size = nSize;
 729             if (scaling > 0)
 730                 oWord.Selection.Font.Scaling = scaling;
 731         }
 732         public void SetFontColor(string strFontColor)
 733         {
 734             switch (strFontColor.ToLower())
 735             {
 736                 case "blue":
 737                     oWord.Selection.Font.Color = 
 738 Microsoft.Office.Interop.Word.WdColor.wdColorBlue;
 739                     break;
 740                 case "gold":
 741                     oWord.Selection.Font.Color = 
 742 Microsoft.Office.Interop.Word.WdColor.wdColorGold;
 743                     break;
 744                 case "gray":
 745                     oWord.Selection.Font.Color = 
 746 Microsoft.Office.Interop.Word.WdColor.wdColorGray875;
 747                     break;
 748                 case "green":
 749                     oWord.Selection.Font.Color = 
 750 Microsoft.Office.Interop.Word.WdColor.wdColorGreen;
 751                     break;
 752                 case "lightblue":
 753                     oWord.Selection.Font.Color = 
 754 Microsoft.Office.Interop.Word.WdColor.wdColorLightBlue;
 755                     break;
 756                 case "orange":
 757                     oWord.Selection.Font.Color = 
 758 Microsoft.Office.Interop.Word.WdColor.wdColorOrange;
 759                     break;
 760                 case "pink":
 761                     oWord.Selection.Font.Color = 
 762 Microsoft.Office.Interop.Word.WdColor.wdColorPink;
 763                     break;
 764                 case "red":
 765                     oWord.Selection.Font.Color = 
 766 Microsoft.Office.Interop.Word.WdColor.wdColorRed;
 767                     break;
 768                 case "yellow":
 769                     oWord.Selection.Font.Color = 
 770 Microsoft.Office.Interop.Word.WdColor.wdColorYellow;
 771                     break;
 772             }
 773         }
 774         public void SetPageNumberAlign(string strType, bool bHeader)
 775         {
 776             object alignment;
 777             object bFirstPage = false;
 778             object bF = true;
 779             //if (bHeader == true)
 780             
 781 //WordApplic.Selection.HeaderFooter.PageNumbers.ShowFirstPageNumber = 
 782 bF;
 783             switch (strType)
 784             {
 785                 case "Center":
 786                     alignment = 
 787 Microsoft.Office.Interop.Word.WdPageNumberAlignment.wdAlignPageNumberCenter;
 788                     
 789 //WordApplic.Selection.HeaderFooter.PageNumbers.Add(ref alignment,ref 
 790 bFirstPage);
 791                     //Microsoft.Office.Interop.Word.Selection 
 792 objSelection = WordApplic.pSelection;
 793                     
 794 oWord.Selection.HeaderFooter.PageNumbers[1].Alignment = 
 795 Microsoft.Office.Interop.Word.WdPageNumberAlignment.wdAlignPageNumberCenter;
 796                     break;
 797                 case "Right":
 798                     alignment = 
 799 Microsoft.Office.Interop.Word.WdPageNumberAlignment.wdAlignPageNumberRight;
 800                     
 801 oWord.Selection.HeaderFooter.PageNumbers[1].Alignment = 
 802 Microsoft.Office.Interop.Word.WdPageNumberAlignment.wdAlignPageNumberRight;
 803                     break;
 804                 case "Left":
 805                     alignment = 
 806 Microsoft.Office.Interop.Word.WdPageNumberAlignment.wdAlignPageNumberLeft;
 807                     oWord.Selection.HeaderFooter.PageNumbers.Add(ref 
 808 alignment, ref bFirstPage);
 809                     break;
 810             }
 811         }
 812         /// <summary>
 813         /// 设置页面为标准A4公文样式
 814         /// </summary>
 815         private void SetA4PageSetup()
 816         {
 817             oWord.ActiveDocument.PageSetup.TopMargin = 
 818 oWord.CentimetersToPoints(3.7f);
 819             //oWord.ActiveDocument.PageSetup.BottomMargin = 
 820 oWord.CentimetersToPoints(1f);
 821             oWord.ActiveDocument.PageSetup.LeftMargin = 
 822 oWord.CentimetersToPoints(2.8f);
 823             oWord.ActiveDocument.PageSetup.RightMargin = 
 824 oWord.CentimetersToPoints(2.6f);
 825             //oWord.ActiveDocument.PageSetup.HeaderDistance = 
 826 oWord.CentimetersToPoints(2.5f);
 827             //oWord.ActiveDocument.PageSetup.FooterDistance = 
 828 oWord.CentimetersToPoints(1f);
 829             oWord.ActiveDocument.PageSetup.PageWidth = 
 830 oWord.CentimetersToPoints(21f);
 831             oWord.ActiveDocument.PageSetup.PageHeight = 
 832 oWord.CentimetersToPoints(29.7f);
 833         }
 834         #endregion
 835         #region 替换
 836         ///<summary>
 837         /// 在word 中查找一个字符串直接替换所需要的文本
 838         /// </summary>
 839         /// <param name="strOldText">原文本</param>
 840         /// <param name="strNewText">新文本</param>
 841         /// <returns></returns>
 842         public bool Replace(string strOldText, string strNewText)
 843         {
 844             if (oDoc == null)
 845                 oDoc = oWord.ActiveDocument;
 846             this.oDoc.Content.Find.Text = strOldText;
 847             object FindText, ReplaceWith, Replace;// 
 848             FindText = strOldText;//要查找的文本
 849             ReplaceWith = strNewText;//替换文本
 850             Replace = 
 851 Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll;/**//*wdReplaceAll -
 852  替换找到的所有项。
 853                                                       * wdReplaceNone - 
 854 不替换找到的任何项。
 855                                                     * wdReplaceOne - 
 856 替换找到的第一项。
 857                                                     * */
 858             oDoc.Content.Find.ClearFormatting();//移除Find的搜索文本和段落格式设置
 859             if (oDoc.Content.Find.Execute(
 860                 ref FindText, ref missing,
 861                 ref missing, ref missing,
 862                 ref missing, ref missing,
 863                 ref missing, ref missing, ref missing,
 864                 ref ReplaceWith, ref Replace,
 865                 ref missing, ref missing,
 866                 ref missing, ref missing))
 867             {
 868                 return true;
 869             }
 870             return false;
 871         }
 872         public bool SearchReplace(string strOldText, string strNewText)
 873         {
 874             object replaceAll = 
 875 Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll;
 876             //首先清除任何现有的格式设置选项,然后设置搜索字符串 strOldText。
 877             oWord.Selection.Find.ClearFormatting();
 878             oWord.Selection.Find.Text = strOldText;
 879             oWord.Selection.Find.Replacement.ClearFormatting();
 880             oWord.Selection.Find.Replacement.Text = strNewText;
 881             if (oWord.Selection.Find.Execute(
 882                 ref missing, ref missing, ref missing, ref missing, ref 
 883 missing,
 884                 ref missing, ref missing, ref missing, ref missing, ref 
 885 missing,
 886                 ref replaceAll, ref missing, ref missing, ref missing, 
 887 ref missing))
 888             {
 889                 return true;
 890             }
 891             return false;
 892         }
 893         #endregion
 894         #region - 表格操作 -
 895         public bool FindTable(string bookmarkTable)
 896         {
 897             try
 898             {
 899                 object bkObj = bookmarkTable;
 900                 if (oWord.ActiveDocument.Bookmarks.Exists(bookmarkTable)
 901  == true)
 902                 {
 903                     oWord.ActiveDocument.Bookmarks.get_Item(ref 
 904 bkObj).Select();
 905                     return true;
 906                 }
 907                 else
 908                     return false;
 909             }
 910             catch (Exception ex)
 911             {
 912                 throw ex;
 913             }
 914         }
 915         public void MoveNextCell()
 916         {
 917             try
 918             {
 919                 Object unit = 
 920 Microsoft.Office.Interop.Word.WdUnits.wdCell;
 921                 Object count = 1;
 922                 oWord.Selection.Move(ref unit, ref count);
 923             }
 924             catch (Exception ex)
 925             {
 926                 throw ex;
 927             }
 928         }
 929         public void SetCellValue(string value)
 930         {
 931             try
 932             {
 933                 oWord.Selection.TypeText(value);
 934             }
 935             catch (Exception ex)
 936             {
 937                 throw ex;
 938             }
 939         }
 940         public void MoveNextRow()
 941         {
 942             try
 943             {
 944                 Object extend = 
 945 Microsoft.Office.Interop.Word.WdMovementType.wdExtend;
 946                 Object unit = 
 947 Microsoft.Office.Interop.Word.WdUnits.wdCell;
 948                 Object count = 1;
 949                 oWord.Selection.MoveRight(ref unit, ref count, ref 
 950 extend);
 951             }
 952             catch (Exception ex)
 953             {
 954                 throw ex;
 955             }
 956         }
 957         //表格操作结束
 958         #endregion 
 959         #region 填充书签
 960         /// <summary>  
 961         /// 填充书签  
 962         /// </summary>  
 963         /// <param name="bookmark">书签</param>  
 964         /// <param name="value"></param>  
 965         public void bookmarkReplace(string bookmark, string value)
 966         {
 967             try
 968             {
 969                 object bkObj = bookmark;
 970                 if (oWord.ActiveDocument.Bookmarks.Exists(bookmark) == 
 971 true)
 972                 {
 973                     oWord.ActiveDocument.Bookmarks.get_Item(ref 
 974 bkObj).Select();
 975                 }
 976                 else return;
 977                 oWord.Selection.TypeText(value);
 978             }
 979             catch (Exception ex)
 980             {
 981                 throw ex;
 982             }
 983         }
 984         #endregion
 985 
 986         /// <summary>
 987         /// rgb转换函数
 988         /// </summary>
 989         /// <param name="r"></param>
 990         /// <param name="g"></param>
 991         /// <param name="b"></param>
 992         /// <returns></returns>
 993         int RGB(int r, int g, int b)
 994         {
 995             return ((b << 16) | (ushort)(((ushort)g << 8) | 
 996 r));
 997         }
 998         Color RGBToColor(int color)
 999         {
1000             int r = 0xFF & color;
1001             int g = 0xFF00 & color;
1002             g >>= 8;
1003             int b = 0xFF0000 & color;
1004             b >>= 16;
1005             return Color.FromArgb(r, g, b);
1006         }
1007     }
1008 }
1009 /*
1010 (1) 插入图片后,如果后面不再插入内容,则图片会包含;如果继续插入内容,则图片会被程序删除。解决方法是:
1011        插入图片后,执行跳转,光标转移到图片后面,再插入东西,就可以了。
1012             word.InsertImage("d://111.jpg",400.0f,300.0f);    //插入图片   
1013             word.GoToTheEnd();
1014  (2)
1015 oWord.ActiveWindow.View.SeekView = 
1016 Microsoft.Office.Interop.Word.WdSeekView.wdSeekCurrentPageHeader; //页眉 
1017 oWord.ActiveWindow.View.SeekView = 
1018 Microsoft.Office.Interop.Word.WdSeekView.wdSeekCurrentPageFooter; //页脚 
1019 oWord.ActiveWindow.View.SeekView = 
1020 Microsoft.Office.Interop.Word.WdSeekView.wdSeekMainDocument; //转到正文
1021 object page = Microsoft.Office.Interop.Word.WdFieldType.wdFieldPage; 
1022 //当前页码
1023 object pages = 
1024 Microsoft.Office.Interop.Word.WdFieldType.wdFieldNumPages;  //总页码
1025  * 
1026 */

示例程序,由于用到了静态类等,直接拷贝可能不能运行:

引入命名空间:using WordAddinSample;

几段代码:

  1 private void button1_Click(object sender, EventArgs e)
  2         {
  3             WordHelp word = new WordHelp();
  4             word.Open();
  5            // word.InsertPageNumber("center"); 插入页码,但注意只是插入到正文里,不是真正的页码位置
  6            // word.LoadDotFile("d://ESTemplate.doc");
  7            // word.CreateWordDocument("d://ab.doc", false); //打开已有文件
  8             word.SetPageNumberAlign("center",true); //
  9             word.InsertText("白龙矿反馈设计报告1111"); //插入文本
 10             word.SetAlignment("center"); //居中  
 11             word.InsertLineBreak(5); //换行,参数为行数,例为换5行
 12             word.SetFont("bold"); //只有三个值bold, Italic Underlined
 13             word.SetFontSize(44); //大小
 14             word.SetFontName("黑体"); //字体样式
 15             word.InsertText("白龙矿反馈设计报告"); //插入文本
 16         
 17             word.SetFont(); //清空字体格式,恢复默认
 18             word.InsertLineBreak();
 19             word.InsertText("美丽的矿大校园--字体已恢复默认");
 20             word.InsertImage("d://111.jpg",400.0f,300.0f);    //插入图片
 21             word.InsertPagebreak(); //分页符
 22             word.InsertText("分页测试2");            
 23             word.InsertLineBreak();
 24             word.InsertText("插入表格");
 25             word.InsertLineBreak();
 26             DataTable storedt = new DataTable();  // Data 数据空间
 27             storedt.Columns.Add("Book_ISBN");
 28             storedt.Columns.Add("Book_Name");
 29             storedt.Columns.Add("Store_Num");
 30             storedt.Columns.Add("CanBorrow_Num");
 31             storedt.Columns.Add("InShop_Num");
 32             storedt.Columns.Add("OutShop_Num");
 33             storedt.Rows.Add("1", "1", "1", "1", "1", "1");
 34             storedt.Rows.Add("2", "2", "2", "2", "2", "2");
 35             storedt.Rows.Add("3", "3", "3", "3", "3", "3");
 36             storedt.Rows.Add("4", "4", "4", "4", "4", "4");
 37             storedt.Rows.Add("5", "5", "5", "5", "5", "5");
 38             storedt.Rows.Add("6", "6", "6", "6", "6", "6");
 39             word.InsertTable(storedt);
 40             word.InsertPageHeader("我是页眉"); //插入页眉
 41             word.InsertPageFooter("我是页脚"); //插入页脚
 42             word.InsertPageFooterNumber(); // 第*页/共*页
 43             word.GoToTheEnd();
 44             word.SaveAs("d://c.doc");
 45             word.Quit();
 46         }
 47         private void button2_Click(object sender, EventArgs e) //加载模版
 48         {
 49             WordHelp word = new WordHelp();
 50            // word.Open(); //先创建个对象
 51             word.LoadDotFile("d://现代型报告.dot");
 52            // word.LoadDotFile("d://现代型报告.dot"); //加载模版 
 53             word.InsertText("huhu");
 54             word.SaveAs("d://temp.doc");
 55             word.Quit();
 56         }
 57         private void button3_Click(object sender, EventArgs e) //打开Word
 58         {
 59             WordHelp word = new WordHelp();
 60             word.CreateWordDocument("d://c.doc", false); //打开已有文件
 61             word.GoToTheEnd();
 62             word.InsertText("我是打开已有文档新添加的文本内容");            
 63             word.Save();
 64             word.Quit();
 65         }
 66         private void button4_Click(object sender, EventArgs e)
 67         {
 68             //静态变量赋值,测试用
 69             setParas();
 70             // word.Open(); //先创建个对象
 71             WordHelp word = new WordHelp();            
 72             //加载模版 
 73             word.LoadDotFile("d://HDTemplate.dot"); 
 74  
 75             //首页
 76             word.SetAlignment("center"); //居中             
 77             word.SetFont("bold"); //只有三个值bold, Italic Underlined
 78             word.SetFontSize(26.25f); //大小 26.25对应 一号
 79             word.SetFontName("黑体"); //字体样式
 80             word.InsertLineBreak(2); //换行,参数为行数,例为换5行
 81             word.InsertText(ClassParas.MineName); //插入文本
 82             word.InsertLineBreak();
 83             word.InsertText("反馈设计报告");
 84             word.InsertLineBreak(8);
 85             word.SetFontSize(18);
 86             word.InsertText(ClassParas.CompanyName);
 87             word.InsertLineBreak();
 88             word.InsertText("中国矿业大学");
 89             word.InsertLineBreak();
 90             word.InsertText(DateTime.Now.ToShortDateString());
 91             word.InsertLineBreak();
 92 
 93             //保存
 94             word.SaveAs("d://temp.doc");
 95             word.Quit();
 96         }
 97         private void setParas(){            
 98             ClassParas.MineName = "白龙矿";
 99             ClassParas.CompanyName = "山东新汶矿业集团";
100         }
101         private void button5_Click(object sender, EventArgs e) //书签替换
102         {
103             // word.Open(); //先创建个对象
104             WordHelp word = new WordHelp();
105             //加载模版 
106             word.LoadDotFile("d://Bookmark.dot");
107             word.GotoBookMark("矿名"); //光标移动到书签"矿名"处
108             word.bookmarkReplace("矿名","金属矿"); //书签替换
109             word.bookmarkReplace("公司名","我的公司");
110             if (word.FindTable("引用表"))
111             {
112                 // 第1行数据  
113                 word.MoveNextRow();
114                 word.SetCellValue("1");
115                 word.MoveNextCell();
116                 word.SetCellValue("HP电脑");
117                 word.MoveNextCell();
118                 word.SetCellValue("");
119                 word.MoveNextCell();
120                 word.SetCellValue("50");
121                 word.MoveNextCell();
122                 word.SetCellValue("250,000");
123                 // 第2行数据  
124                 word.MoveNextRow();
125                 word.SetCellValue("2");
126                 word.MoveNextCell();
127                 word.SetCellValue("DELL笔记本");
128                 word.MoveNextCell();
129                 word.SetCellValue("");
130                 word.MoveNextCell();
131                 word.SetCellValue("10");
132                 word.MoveNextCell();
133                 word.SetCellValue("40,000");          
134             }  

非常好的几篇参考文章:

C#操作Word辅助类(word2003)

功能全面的一个类,本文中的类即在该类的基础上修改而来

C#编写的Word操作类,有换页,添加表格,文本功能

添加文本、表格、换页
用C#编程修改Word模版

利用模版新建文档,书签的使用,利用书签定位,表格的操作

原文地址:https://www.cnblogs.com/oracleblogs/p/3386433.html