• 【小丸类库系列】Word操作类


       1 using Microsoft.Office.Interop.Word;
       2 using System;
       3 using System.Collections.Generic;
       4 using System.Drawing;
       5 using System.IO;
       6 using System.Linq;
       7 using System.Reflection;
       8 using System.Text.RegularExpressions;
       9 
      10 namespace OtaReportTool
      11 {
      12     public class WordHelper
      13     {
      14         #region 成员变量
      15 
      16         private bool isWordVisible = false;
      17         private object missing = Missing.Value;
      18         private Application app;
      19         private Document doc;
      20 
      21         #endregion 成员变量
      22 
      23         #region 构造函数
      24 
      25         /// <summary>
      26         /// 构造函数,新建一个工作簿
      27         /// </summary>
      28         public WordHelper()
      29         {
      30             app = new Application();
      31             app.Visible = isWordVisible;
      32             doc = app.Documents.Add(ref missing, ref missing, ref missing, ref missing);
      33         }
      34 
      35         /// <summary>
      36         /// 构造函数,打开一个已有的工作簿
      37         /// </summary>
      38         /// <param name="fileName">Excel文件名</param>
      39         public WordHelper(string fileName)
      40         {
      41             if (!File.Exists(fileName))
      42                 throw new Exception("指定路径的Word文件不存在!");
      43 
      44             //创建Word进程
      45             app = new Application();
      46             app.Visible = isWordVisible;
      47 
      48             //打开Word文件
      49             object objFileName = fileName;
      50             object objIsWordVisible = isWordVisible;
      51             object objIsWordReadOnly = true;
      52             object objEncoding = Microsoft.Office.Core.MsoEncoding.msoEncodingUTF8;
      53             doc = app.Documents.Open(ref objFileName,
      54                 ref missing, ref objIsWordReadOnly, ref missing,
      55                 ref missing, ref missing, ref missing, ref missing,
      56                 ref missing, ref missing, ref objEncoding, ref objIsWordVisible,
      57                 ref missing, ref missing, ref missing, ref missing);
      58             doc.Activate();
      59 
      60             //将视图从 页面视图 切换到 普通视图,避免因为分页计算而延迟word响应时间
      61             if (doc.ActiveWindow.View.SplitSpecial == WdSpecialPane.wdPaneNone)
      62             {
      63                 doc.ActiveWindow.ActivePane.View.Type = WdViewType.wdNormalView;
      64             }
      65             else
      66             {
      67                 doc.ActiveWindow.View.Type = WdViewType.wdNormalView;
      68             }
      69         }
      70 
      71         #endregion 构造函数
      72 
      73         #region 文本操作
      74 
      75         /// <summary>
      76         /// 设置字体
      77         /// </summary>
      78         /// <param name="sFontName"></param>
      79         public void SetFont(string sFontName)
      80         {
      81             doc.Select();
      82             app.Selection.Font.Name = sFontName;
      83         }
      84 
      85         /// <summary>
      86         /// 插入文本 Inserts the specified text.
      87         /// </summary>
      88         /// <param name="text"></param>
      89         public void InsertText(string text)
      90         {
      91             app.Selection.TypeText(text);
      92         }
      93 
      94         /// <summary>
      95         /// Enter(换行) Inserts a new, blank paragraph.
      96         /// </summary>
      97         public void InsertLineBreak()
      98         {
      99             app.Selection.TypeParagraph();
     100         }
     101 
     102         /// <summary>
     103         /// 插入分页符
     104         /// </summary>
     105         public void InsertBreak()
     106         {
     107             Paragraph para = doc.Content.Paragraphs.Add(missing);
     108             object pBreak = (int)WdBreakType.wdSectionBreakNextPage;
     109             para.Range.InsertBreak(ref pBreak);
     110         }
     111 
     112         /// <summary>
     113         /// 插入图片(图片大小自适应)
     114         /// </summary>
     115         /// <param name="fileName">图片名(包含路径)</param>
     116         public void InsertPic(string fileName)
     117         {
     118             object range = app.Selection.Range;
     119             InsertPic(fileName, missing, missing, range);
     120         }
     121 
     122         /// <summary>
     123         /// 插入图片(带标题)
     124         /// </summary>
     125         /// <param name="fileName">图片名</param>
     126         /// <param name="caption">标题</param>
     127         public void InsertPic(string fileName, string caption)
     128         {
     129             object range = app.Selection.Range;
     130             InsertPic(fileName, missing, missing, range, 0, 0, caption);
     131         }
     132 
     133         /// <summary>
     134         /// 插入图片
     135         /// </summary>
     136         /// <param name="fileName">图片名(包含路径)</param>
     137         /// <param name="width">设置宽度</param>
     138         /// <param name="height">设置高度</param>
     139         public void InsertPic(string fileName, float width, float height)
     140         {
     141             object range = app.Selection.Range;
     142             InsertPic(fileName, missing, missing, range, width, height);
     143         }
     144 
     145         /// <summary>
     146         /// 插入图片(带标题)
     147         /// </summary>
     148         /// <param name="fileName">图片名(包含路径)</param>
     149         /// <param name="width">设置宽度</param>
     150         /// <param name="height">设置高度<</param>
     151         /// <param name="caption">标题或备注文字</param>
     152         public void InsertPic(string fileName, float width, float height, string caption)
     153         {
     154             object range = app.Selection.Range;
     155             InsertPic(fileName, missing, missing, range, width, height, caption);
     156         }
     157 
     158         /// <summary>
     159         /// 插入图片(带标题)
     160         /// </summary>
     161         public void InsertPic(string FileName, object LinkToFile, object SaveWithDocument, object Range, float Width, float Height, string caption)
     162         {
     163             app.Selection.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref Range).Select();
     164             if (Width > 0)
     165             {
     166                 app.Selection.InlineShapes[1].Width = Width;
     167             }
     168             if (Height > 0)
     169             {
     170                 app.Selection.InlineShapes[1].Height = Height;
     171             }
     172 
     173             object Label = WdCaptionLabelID.wdCaptionFigure;
     174             object Title = caption;
     175             object TitleAutoText = "";
     176             object Position = WdCaptionPosition.wdCaptionPositionBelow;
     177             object ExcludeLabel = true;
     178             app.Selection.InsertCaption(ref Label, ref Title, ref TitleAutoText, ref Position, ref ExcludeLabel);
     179             MoveRight();
     180         }
     181 
     182         /// <summary>
     183         /// Adds a picture to a document.
     184         /// </summary>
     185         /// <param name="FileName">Required String. The path and file name of the picture.</param>
     186         /// <param name="LinkToFile">Optional Object. True to link the picture to the file from which it was created. False to make the picture an independent copy of the file. The default value is False.</param>
     187         /// <param name="SaveWithDocument">Optional Object. True to save the linked picture with the document. The default value is False.</param>
     188         /// <param name="Range">Optional Object. The location where the picture will be placed in the text. If the range isn't collapsed, the picture replaces the range; otherwise, the picture is inserted. If this argument is omitted, the picture is placed automatically.</param>
     189         /// <param name="Width">Sets the width of the specified object, in points. </param>
     190         /// <param name="Height">Sets the height of the specified inline shape. </param>
     191         public void InsertPic(string FileName, object LinkToFile, object SaveWithDocument, object Range, float Width, float Height)
     192         {
     193             app.Selection.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref Range).Select();
     194             app.Selection.InlineShapes[1].Width = Width;
     195             app.Selection.InlineShapes[1].Height = Height;
     196             MoveRight();
     197         }
     198 
     199         /// <summary>/// Adds a picture to a document.
     200         /// </summary>
     201         /// <param name="FileName">Required String. The path and file name of the picture.</param>
     202         /// <param name="LinkToFile">Optional Object. True to link the picture to the file from which it was created. False to make the picture an independent copy of the file. The default value is False.</param>
     203         /// <param name="SaveWithDocument">Optional Object. True to save the linked picture with the document. The default value is False.</param>
     204         /// <param name="Range">Optional Object. The location where the picture will be placed in the text. If the range isn't collapsed, the picture replaces the range; otherwise, the picture is inserted. If this argument is omitted, the picture is placed automatically.</param>
     205         public void InsertPic(string FileName, object LinkToFile, object SaveWithDocument, object Range)
     206         {
     207             app.Selection.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref Range);
     208         }
     209 
     210         /// <summary>
     211         /// 获取段落的文本
     212         /// </summary>
     213         /// <param name="index">段落编号</param>
     214         /// <returns></returns>
     215         public string Paragraph(int index)
     216         {
     217             Paragraph para = doc.Content.Paragraphs[index];   ///这是一个设定对应的某一段
     218             return para.Range.Text;
     219         }
     220 
     221         public void DeleteParagraph(int index)
     222         {
     223             Paragraph para = doc.Content.Paragraphs[index];   ///这是一个设定对应的某一段
     224             para.Range.Delete();
     225             return;
     226         }
     227 
     228         public string Section(int index)
     229         {
     230             return doc.Sections[index].Range.Text;
     231         }
     232 
     233         public void DeleteSection(int index)
     234         {
     235             Sections secs = doc.Sections;
     236             Section sec = secs[index];
     237 
     238             sec.Range.Delete();
     239             return;
     240         }
     241 
     242         /// <summary>
     243         /// 替换文档中的文本
     244         /// </summary>
     245         /// <param name="oldString">原有内容</param>
     246         /// <param name="newString">替换后的内容</param>
     247         public void ReplaceString(string oldString, string newString)
     248         {
     249             doc.Content.Find.Text = oldString;
     250             object FindText, ReplaceWith, ReplaceAll;
     251             FindText = oldString;
     252             ReplaceWith = newString;
     253             ReplaceAll = WdReplace.wdReplaceAll;
     254             doc.Content.Find.Execute(ref FindText,
     255                                       ref missing,
     256                                       ref missing,
     257                                       ref missing,
     258                                       ref missing,
     259                                       ref missing,
     260                                       ref missing,
     261                                       ref missing,
     262                                       ref missing,
     263                                       ref ReplaceWith,
     264                                       ref ReplaceAll,
     265                                       ref missing,
     266                                       ref missing,
     267                                       ref missing,
     268                                       ref missing);
     269         }
     270 
     271         /// <summary>
     272         /// 获取word文档的纯文本
     273         /// </summary>
     274         /// <returns></returns>
     275         public string GetText()
     276         {
     277             return doc.Content.Text;
     278         }
     279 
     280         #endregion 文本操作
     281 
     282         #region 格式操作
     283 
     284         /// <summary>
     285         /// 设置对齐方式
     286         /// </summary>
     287         /// <param name="rng"></param>
     288         /// <param name="alignment"></param>
     289         /// <returns></returns>
     290         public WdParagraphAlignment SetAlignment(Range rng, Alignment alignment)
     291         {
     292             rng.ParagraphFormat.Alignment = SetAlignment(alignment);
     293             return SetAlignment(alignment);
     294         }
     295 
     296         public WdParagraphAlignment SetAlignment(Alignment alignment)
     297         {
     298             if (alignment == Alignment.居中)
     299             {
     300                 return WdParagraphAlignment.wdAlignParagraphCenter;
     301             }
     302             else if (alignment == Alignment.左对齐)
     303             {
     304                 return WdParagraphAlignment.wdAlignParagraphLeft;
     305             }
     306             else
     307             { return WdParagraphAlignment.wdAlignParagraphRight; }
     308         }
     309 
     310         //字体格式设定
     311         public void GetWordFont(Microsoft.Office.Interop.Word.Font wordFont, System.Drawing.Font font)
     312         {
     313             wordFont.Name = font.Name;
     314             wordFont.Size = font.Size;
     315             if (font.Bold) { wordFont.Bold = 1; }
     316             if (font.Italic) { wordFont.Italic = 1; }
     317             if (font.Underline == true)
     318             {
     319                 wordFont.Underline = WdUnderline.wdUnderlineNone;
     320             }
     321             wordFont.UnderlineColor = WdColor.wdColorAutomatic;
     322 
     323             if (font.Strikeout)
     324             {
     325                 wordFont.StrikeThrough = 1;//删除线
     326             }
     327         }
     328 
     329         public void SetCenterAlignment()
     330         {
     331             app.Selection.Range.ParagraphFormat.Alignment = SetAlignment(Alignment.居中);
     332         }
     333 
     334         #endregion 格式操作
     335 
     336         #region 表格操作
     337 
     338         /// <summary>
     339         /// 获取表格
     340         /// </summary>
     341         /// <param name="index">段落编号</param>
     342         /// <returns></returns>
     343         public Table Table(int index)
     344         {
     345             Table table = doc.Tables[index];   ///这是一个设定对应的某一段
     346             return table;
     347         }
     348 
     349         public string ReadTableContent(int tableIdx, int rowIdx, int colIdx)
     350         {
     351             return doc.Tables[tableIdx].Cell(rowIdx, colIdx).Range.Text.Trim('
    ', 'a', '
    ').Trim();
     352         }
     353 
     354         public string ReadTableContent(Table table, int rowIdx, int colIdx)
     355         {
     356             try
     357             {
     358                 return table.Cell(rowIdx, colIdx).Range.Text.Trim('
    ', 'a', '
    ').Trim();
     359             }
     360             catch (Exception)
     361             {
     362                 return string.Empty;
     363             }
     364         }
     365 
     366         public int GetTableRowCount(int tableIdx)
     367         {
     368             return doc.Tables[tableIdx].Rows.Count;
     369         }
     370 
     371         public Table GetTable(int tableIndex)
     372         {
     373             if (doc.Tables.Count >= tableIndex)
     374             {
     375                 return doc.Tables[tableIndex];
     376             }
     377             return null;
     378         }
     379 
     380         public Table InsertTableRow(Table table)
     381         {
     382             if (table != null)
     383             {
     384                 table.Rows.Add();
     385             }
     386 
     387             return table;
     388         }
     389 
     390         public Table InsertTableColumn(Table table)
     391         {
     392             if (table != null)
     393             {
     394                 table.Columns.Add();
     395             }
     396             return table;
     397         }
     398 
     399         public Table InsertTableColumns(Table table, int columnCount)
     400         {
     401             for (int i = 0; i < columnCount; i++)
     402             {
     403                 table = InsertTableColumn(table);
     404             }
     405             return table;
     406         }
     407 
     408         public Table DeleteTableRows(Table table, List<int> rowIndexs)
     409         {
     410             if (table != null)
     411             {
     412                 foreach (var i in rowIndexs)
     413                 {
     414                     table = DeleteTableRow(table, i);
     415                 }
     416             }
     417             return table;
     418         }
     419 
     420         public Table DeleteTableRow(Table table, int rowIndex)
     421         {
     422             try
     423             {
     424                 if (table != null)
     425                 {
     426                     table.Rows[rowIndex].Delete();
     427                 }
     428             }
     429             catch (Exception ex)
     430             {
     431                 throw new Exception(ex.Message);
     432             }
     433 
     434             return table;
     435         }
     436 
     437         /// <summary>
     438         /// 删除单元格
     439         /// </summary>
     440         /// <param name="table"></param>
     441         /// <param name="rowIndex"></param>
     442         /// <param name="columnIndex"></param>
     443         /// <param name="shiftcells">删除类型</param>
     444         /// wdDeleteCellsEntireColumn   3    Delete the entire column of cells from the table.
     445         /// wdDeleteCellsEntireRow      2    Delete the entire row of cells from the table.
     446         /// wdDeleteCellsShiftLeft      0    Shift remaining cells left in the row where the deletion occurred after a cell or range of cells has been deleted.
     447         /// wdDeleteCellsShiftUp        1    Shift remaining cells up in the column where the deletion occurred after a cell or range of cells has been deleted.
     448         /// <returns></returns>
     449         public Table DeleteTableCell(Table table, int rowIndex, int columnIndex, int shiftcells)
     450         {
     451             try
     452             {
     453                 if (table != null)
     454                 {
     455                     table.Cell(rowIndex, columnIndex).Delete(shiftcells);
     456                 }
     457             }
     458             catch (Exception ex)
     459             {
     460                 throw new Exception(ex.Message);
     461             }
     462 
     463             return table;
     464         }
     465 
     466         public Table DeleteTableColumn(Table table, int columnIndex)
     467         {
     468             try
     469             {
     470                 if (table != null)
     471                 {
     472                     table.Columns[columnIndex].Delete();
     473                 }
     474             }
     475             catch (Exception ex)
     476             {
     477                 throw new Exception(ex.Message);
     478             }
     479 
     480             return table;
     481         }
     482 
     483         public bool WriteTableCellContent(Table table, int rowIndex, int colIndex, string content)
     484         {
     485             try
     486             {
     487                 table.Cell(rowIndex, colIndex).Range.Delete();
     488                 table.Cell(rowIndex, colIndex).Range.Text = content;
     489             }
     490             catch (Exception exception)
     491             {
     492                 return false;
     493             }
     494             return true;
     495         }
     496 
     497         public bool DeleteTableCellContent(Table table, int rowIndex, int colIndex)
     498         {
     499             try
     500             {
     501                 table.Cell(rowIndex, colIndex).Range.Delete();
     502             }
     503             catch (Exception exception)
     504             {
     505                 return false;
     506             }
     507             return true;
     508         }
     509 
     510         public int GetTableCount()
     511         {
     512             int tableCount = 0;
     513             try
     514             {
     515                 tableCount = doc.Tables.Count;
     516             }
     517             catch (Exception exception)
     518             {
     519             }
     520             return tableCount;
     521         }
     522 
     523         public bool DeleteTable(int index)
     524         {
     525             try
     526             {
     527                 doc.Tables[index].Delete();
     528             }
     529             catch (Exception exception)
     530             {
     531                 return false;
     532             }
     533             return true;
     534         }
     535 
     536         public bool DeleteTable(Table table)
     537         {
     538             try
     539             {
     540                 table.Delete();
     541             }
     542             catch (Exception exception)
     543             {
     544                 return false;
     545             }
     546             return true;
     547         }
     548 
     549         public bool DeleteTables(List<int> tableIndexs)
     550         {
     551             try
     552             {
     553                 if (tableIndexs.Count > 0)
     554                 {
     555                     foreach (var i in tableIndexs)
     556                     {
     557                         doc.Tables[i].Delete();
     558                     }
     559                 }
     560             }
     561             catch (Exception exception)
     562             {
     563                 return false;
     564             }
     565             return true;
     566         }
     567 
     568         public void MergeRowCells(int tableIndexs, int rowIndex)
     569         {
     570             try
     571             {
     572                 doc.Tables[tableIndexs].Rows[rowIndex].Cells.Merge();
     573             }
     574             catch (Exception exception)
     575             {
     576             }
     577         }
     578 
     579         public void MergeRowCells(Table table, int rowIndex)
     580         {
     581             try
     582             {
     583                 table.Rows[rowIndex].Cells.Merge();
     584             }
     585             catch (Exception exception)
     586             {
     587             }
     588         }
     589 
     590         public void MergeColumnCells(Table table, int columnIndex)
     591         {
     592             try
     593             {
     594                 table.Columns[columnIndex].Cells.Merge();
     595             }
     596             catch (Exception exception)
     597             {
     598             }
     599         }
     600 
     601         public void MergeCells(Table table, int rowIndex, int columnIndex, int rowIndex2, int columnIndex2)
     602         {
     603             try
     604             {
     605                 table.Cell(rowIndex, columnIndex).Merge(table.Cell(rowIndex2, columnIndex2));
     606             }
     607             catch (Exception exception)
     608             {
     609             }
     610         }
     611 
     612         public void MergeCells2(Table table, int rowIndex, int columnIndex, int length)
     613         {
     614             try
     615             {
     616                 table.Cell(rowIndex, columnIndex).Select();    //选中一行
     617                 object moveUnit1 = WdUnits.wdLine;
     618                 object moveCount1 = length;
     619                 object moveExtend1 = WdMovementType.wdExtend;
     620                 app.Selection.MoveDown(ref moveUnit1, ref moveCount1, ref moveExtend1);
     621                 app.Selection.Cells.Merge();
     622             }
     623             catch (Exception exception)
     624             {
     625             }
     626         }
     627 
     628         //插入表格 -
     629         public bool InsertTable(System.Data.DataTable dt, bool haveBorder, float[] colWidths)
     630         {
     631             try
     632             {
     633                 object missing = System.Reflection.Missing.Value;
     634 
     635                 int lenght = doc.Characters.Count - 1;
     636                 object start = lenght;
     637                 object end = lenght;
     638 
     639                 //表格起始坐标
     640                 Range tableLocation = doc.Range(ref start, ref end);
     641 
     642                 //添加Word表格
     643                 Table table = doc.Tables.Add(tableLocation, dt.Rows.Count + 1, dt.Columns.Count, ref missing, ref missing);//Word.WdAutoFitBehavior.wdAutoFitContent,Word.WdAutoFitBehavior.wdAutoFitWindow);
     644 
     645                 if (colWidths != null)
     646                 {
     647                     for (int i = 0; i < colWidths.Length; i++)
     648                     {
     649                         table.Columns[i + 1].Width = (float)(28.5F * colWidths[i]);
     650                     }
     651                 }
     652 
     653                 ///设置TABLE的样式
     654                 table.Rows.HeightRule = WdRowHeightRule.wdRowHeightAtLeast;
     655                 table.Rows.Height = app.CentimetersToPoints(float.Parse("0.8"));
     656                 table.Range.Font.Size = 10.5F;
     657                 table.Range.Font.Name = "宋体";
     658                 table.Range.Font.Bold = 0;
     659                 table.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;
     660                 table.Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter;
     661 
     662                 if (haveBorder == true)
     663                 {
     664                     //设置外框样式
     665                     table.Borders.OutsideLineStyle = WdLineStyle.wdLineStyleSingle;
     666                     table.Borders.InsideLineStyle = WdLineStyle.wdLineStyleSingle;
     667                     //样式设置结束
     668                 }
     669                 for (int i = 1; i <= dt.Columns.Count; i++)
     670                 {
     671                     string colname = dt.Columns[i - 1].ColumnName;
     672                     table.Cell(1, i).Range.Text = colname;
     673                 }
     674 
     675                 for (int row = 0; row < dt.Rows.Count; row++)
     676                 {
     677                     for (int col = 0; col < dt.Columns.Count; col++)
     678                     {
     679                         table.Cell(row + 2, col + 1).Range.Text = dt.Rows[row][col].ToString();
     680                     }
     681                 }
     682 
     683                 return true;
     684             }
     685             catch (Exception e)
     686             {
     687                 Console.WriteLine((e.ToString()));
     688                 return false;
     689             }
     690             finally
     691             {
     692             }
     693         }
     694 
     695         public bool InsertTable(System.Data.DataTable dt, bool haveBorder)
     696         {
     697             return InsertTable(dt, haveBorder, null);
     698         }
     699 
     700         public bool InsertTable(System.Data.DataTable dt)
     701         {
     702             return InsertTable(dt, false, null);
     703         }
     704 
     705         #endregion 表格操作
     706 
     707         #region 查找替换
     708 
     709         /// <summary>
     710         /// 获得字符的所在Paragraph的index(耗时过长不建议使用)
     711         /// </summary>
     712         /// <param name="strKey"></param>
     713         /// <returns></returns>
     714         public int FindParagraph(string strKey)
     715         {
     716             int i = 0;
     717             Find wfnd;
     718             if (doc.Paragraphs != null && doc.Paragraphs.Count > 0)
     719             {
     720                 for (i = 1; i <= doc.Paragraphs.Count; i++)
     721                 {
     722                     wfnd = doc.Paragraphs[i].Range.Find;
     723                     wfnd.ClearFormatting();
     724                     wfnd.Text = strKey;
     725                     if (wfnd.Execute(ref missing, ref missing,
     726                         ref missing, ref missing,
     727                         ref missing, ref missing,
     728                         ref missing, ref missing,
     729                         ref missing, ref missing,
     730                         ref missing, ref missing,
     731                         ref missing, ref missing,
     732                         ref missing))
     733                     {
     734                         return i;
     735                     }
     736                 }
     737             }
     738             return -1;
     739         }
     740 
     741         /// <summary>
     742         /// 删除字符的所在段落(耗时过长不建议使用)
     743         /// </summary>
     744         /// <param name="strKeys"></param>
     745         public void DeleteParagraphByKeywords(List<string> strKeys)
     746         {
     747             List<int> indexDeleted = new List<int>();
     748 
     749             int i = 0;
     750             Find wfnd;
     751             if (doc.Paragraphs != null && doc.Paragraphs.Count > 0)
     752             {
     753                 for (i = 1; i <= doc.Paragraphs.Count; i++)
     754                 {
     755                     wfnd = doc.Paragraphs[i].Range.Find;
     756                     wfnd.ClearFormatting();
     757                     foreach (string strKey in strKeys)
     758                     {
     759                         wfnd.Text = strKey;
     760                         if (wfnd.Execute(ref missing, ref missing,
     761                       ref missing, ref missing,
     762                       ref missing, ref missing,
     763                       ref missing, ref missing,
     764                       ref missing, ref missing,
     765                       ref missing, ref missing,
     766                       ref missing, ref missing,
     767                       ref missing))
     768                         {
     769                             indexDeleted.Add(i);
     770                         }
     771                     }
     772                 }
     773             }
     774             foreach (int index in indexDeleted.OrderByDescending(x => x).ToList())
     775             {
     776                 DeleteParagraph(index);
     777             }
     778         }
     779 
     780         /// <summary>
     781         /// 删除字符的所在段落
     782         /// </summary>
     783         /// <param name="FindWord"></param>
     784         /// <returns></returns>
     785         public bool DeleteParagraphByKeywords(string FindWord)
     786         {
     787             bool findover = false;
     788             Selection currentselect = app.Selection;//实例化一个selection接口
     789             WdUnits storyUnit = WdUnits.wdStory;
     790             currentselect.HomeKey(storyUnit);
     791             currentselect.Find.ClearFormatting();
     792             currentselect.Find.Text = FindWord;//查询的文字
     793             currentselect.Find.Wrap = WdFindWrap.wdFindStop;//查询完成后停止
     794             findover = currentselect.Find.Execute(ref missing, ref missing,
     795                           ref missing, ref missing,
     796                           ref missing, ref missing,
     797                           ref missing, ref missing,
     798                           ref missing, ref missing,
     799                           ref missing, ref missing,
     800                           ref missing, ref missing,
     801                           ref missing);
     802             WdUnits paraUnit = WdUnits.wdParagraph;
     803             currentselect.Expand(paraUnit);
     804             currentselect.Range.Delete();
     805             return findover;
     806         }
     807 
     808         /// <summary>
     809         /// 判断文档中是否含有特定字符
     810         /// </summary>
     811         /// <param name="strKey"></param>
     812         /// <returns></returns>
     813         public bool HasWord(string strKey)
     814         {
     815             doc.Content.Find.Text = strKey;
     816             if (doc.Content.Find.Execute(ref missing, ref missing,
     817                     ref missing, ref missing,
     818                     ref missing, ref missing,
     819                     ref missing, ref missing,
     820                     ref missing, ref missing,
     821                     ref missing, ref missing,
     822                     ref missing, ref missing,
     823                     ref missing))
     824             {
     825                 return true;
     826             }
     827             else
     828             {
     829                 return false;
     830             }
     831         }
     832 
     833         /// <summary>
     834         /// 将特定字符改为黄色
     835         /// </summary>
     836         /// <param name="FindWord"></param>
     837         /// <returns></returns>
     838         public bool MarkWord(string FindWord)
     839         {
     840             bool findover = false;
     841             Selection currentselect = app.Selection;//实例化一个selection接口
     842             currentselect.Find.ClearFormatting();
     843             currentselect.Find.Text = FindWord;//查询的文字
     844             currentselect.Find.Wrap = WdFindWrap.wdFindStop;//查询完成后停止
     845             findover = currentselect.Find.Execute(ref missing, ref missing,
     846                           ref missing, ref missing,
     847                           ref missing, ref missing,
     848                           ref missing, ref missing,
     849                           ref missing, ref missing,
     850                           ref missing, ref missing,
     851                           ref missing, ref missing,
     852                           ref missing);
     853             currentselect.Font.Color = WdColor.wdColorYellow;//设置颜色为黄
     854             return findover;
     855         }
     856 
     857         /// <summary>
     858         /// 替换文字
     859         /// </summary>
     860         /// <param name="oldText">待替换的文本</param>
     861         /// <param name="newText">替换后的文本</param>
     862         /// <param name="range">范围</param>
     863         /// <returns></returns>
     864         public bool Replace(string oldText, string newText, Range range)
     865         {
     866             object matchCase = false;
     867             object findText = oldText;
     868             object replaceWith = newText;
     869             object wdReplace = WdReplace.wdReplaceOne;
     870             return range.Find.Execute(ref findText, ref matchCase, ref missing, ref missing,
     871                   ref missing, ref missing, ref missing, ref missing, ref missing, ref replaceWith,
     872                   ref wdReplace, ref missing, ref missing, ref missing, ref missing);
     873         }
     874 
     875         /// <summary>
     876         /// 替换
     877         /// </summary>
     878         /// <param name="oldText">待替换的文本</param>
     879         /// <param name="newText">替换后的文本</param>
     880         /// <param name="replaceType">All:替换所有、None:不替换、FirstOne:替换第一个</param>
     881         /// <param name="isCaseSensitive">大小写是否敏感</param>
     882         /// <returns></returns>
     883         public bool Replace(string oldText, string newText, string replaceType, bool isCaseSensitive)
     884         {
     885             if (doc == null)
     886             {
     887                 doc = app.ActiveDocument;
     888             }
     889             object findText = oldText;
     890             object replaceWith = newText;
     891             object wdReplace;
     892             object matchCase = isCaseSensitive;
     893             switch (replaceType)
     894             {
     895                 case "All":
     896                     wdReplace = WdReplace.wdReplaceAll;
     897                     break;
     898 
     899                 case "None":
     900                     wdReplace = WdReplace.wdReplaceNone;
     901                     break;
     902 
     903                 case "FirstOne":
     904                     wdReplace = WdReplace.wdReplaceOne;
     905                     break;
     906 
     907                 default:
     908                     wdReplace = WdReplace.wdReplaceOne;
     909                     break;
     910             }
     911             doc.Content.Find.ClearFormatting();//移除Find的搜索文本和段落格式设置
     912 
     913             return doc.Content.Find.Execute(ref findText, ref matchCase, ref missing, ref missing,
     914                   ref missing, ref missing, ref missing, ref missing, ref missing, ref replaceWith,
     915                   ref wdReplace, ref missing, ref missing, ref missing, ref missing);
     916         }
     917 
     918         /// <summary>
     919         /// 替换指定Paragraph中的文本
     920         /// </summary>
     921         /// <param name="oldText"></param>
     922         /// <param name="newText"></param>
     923         /// <param name="replaceType"></param>
     924         /// <param name="isCaseSensitive"></param>
     925         /// <param name="index"></param>
     926         /// <returns></returns>
     927         public bool Replace(string oldText, string newText, string replaceType, bool isCaseSensitive, int index)
     928         {
     929             if (doc == null)
     930             {
     931                 doc = app.ActiveDocument;
     932             }
     933             object findText = oldText;
     934             object replaceWith = newText;
     935             object wdReplace;
     936             object matchCase = isCaseSensitive;
     937             switch (replaceType)
     938             {
     939                 case "All":
     940                     wdReplace = WdReplace.wdReplaceAll;
     941                     break;
     942 
     943                 case "None":
     944                     wdReplace = WdReplace.wdReplaceNone;
     945                     break;
     946 
     947                 case "FirstOne":
     948                     wdReplace = WdReplace.wdReplaceOne;
     949                     break;
     950 
     951                 default:
     952                     wdReplace = WdReplace.wdReplaceOne;
     953                     break;
     954             }
     955             doc.Content.Find.ClearFormatting();//移除Find的搜索文本和段落格式设置
     956             return doc.Paragraphs[index].Range.Find.Execute(ref findText, ref matchCase, ref missing, ref missing,
     957                   ref missing, ref missing, ref missing, ref missing, ref missing, ref replaceWith,
     958                   ref wdReplace, ref missing, ref missing, ref missing, ref missing);
     959         }
     960 
     961         #endregion 查找替换
     962 
     963         #region 复制粘贴
     964 
     965         /// <summary>
     966         /// 复制
     967         /// </summary>
     968         public void Copy()
     969         {
     970             app.Selection.Copy();
     971         }
     972 
     973         /// <summary>
     974         /// 全选文档
     975         /// </summary>
     976         public void Paste()
     977         {
     978             app.Selection.Paste();
     979         }
     980 
     981         #endregion 复制粘贴
     982 
     983         #region 光标位置
     984 
     985         /// <summary>
     986         /// 全选文档
     987         /// </summary>
     988         public void SelectWholeDocument()
     989         {
     990             app.Selection.WholeStory();
     991         }
     992 
     993         /// <summary>
     994         /// 移动到文档起始位置
     995         /// </summary>
     996         public void MoveToTop()
     997         {
     998             app.Selection.HomeKey(WdUnits.wdStory);
     999         }
    1000 
    1001         /// <summary>
    1002         /// 移动到文档结束位置
    1003         /// </summary>
    1004         public void MoveToBottom()
    1005         {
    1006             app.Selection.EndKey(WdUnits.wdStory);
    1007         }
    1008 
    1009         /// <summary>
    1010         /// 光标移动到指定书签位置,书签不存在时不移动
    1011         /// </summary>
    1012         /// <param name="bookMarkName"></param>
    1013         /// <returns></returns>
    1014         public bool GoToBookMark(string bookMarkName)
    1015         {
    1016             //是否存在书签
    1017             if (doc.Bookmarks.Exists(bookMarkName))
    1018             {
    1019                 object what = WdGoToItem.wdGoToBookmark;
    1020                 object name = bookMarkName;
    1021                 GoTo(what, missing, missing, name);
    1022                 return true;
    1023             }
    1024             return false;
    1025         }
    1026 
    1027         /// <summary>
    1028         /// 移动光标
    1029         /// Moves the insertion point to the character position immediately preceding the specified item.
    1030         /// </summary>
    1031         /// <param name="what">Optional Object. The kind of item to which the selection is moved. Can be one of the WdGoToItem constants.</param>
    1032         /// <param name="which">Optional Object. The item to which the selection is moved. Can be one of the WdGoToDirection constants. </param>
    1033         /// <param name="count">Optional Object. The number of the item in the document. The default value is 1.</param>
    1034         /// <param name="name">Optional Object. If the What argument is wdGoToBookmark, wdGoToComment, wdGoToField, or wdGoToObject, this argument specifies a name.</param>
    1035         public void GoTo(object what, object which, object count, object name)
    1036         {
    1037             app.Selection.GoTo(ref what, ref which, ref count, ref name);
    1038         }
    1039 
    1040         /// <summary>
    1041         /// 光标上移
    1042         /// Moves the selection up and returns the number of units it's been moved.
    1043         /// </summary>
    1044         /// <param name="unit">Optional Object. The unit by which to move the selection. Can be one of the following WdUnits constants: wdLine, wdParagraph, wdWindow or wdScreen etc. The default value is wdLine.</param>
    1045         /// <param name="count">Optional Object. The number of units the selection is to be moved. The default value is 1.</param>
    1046         /// <param name="extend">Optional Object. Can be either wdMove or wdExtend. If wdMove is used, the selection is collapsed to the end point and moved up. If wdExtend is used, the selection is extended up. The default value is wdMove.</param>
    1047         /// <returns></returns>
    1048         public void MoveUp(int num = 1)
    1049         {
    1050             object unit = WdUnits.wdCharacter;
    1051             object count = num;
    1052             MoveUp(unit, count, missing);
    1053         }
    1054 
    1055         /// <summary>
    1056         /// 光标上移
    1057         /// Moves the selection up and returns the number of units it's been moved.
    1058         /// </summary>
    1059         /// <param name="unit">Optional Object. The unit by which to move the selection. Can be one of the following WdUnits constants: wdLine, wdParagraph, wdWindow or wdScreen etc. The default value is wdLine.</param>
    1060         /// <param name="count">Optional Object. The number of units the selection is to be moved. The default value is 1.</param>
    1061         /// <param name="extend">Optional Object. Can be either wdMove or wdExtend. If wdMove is used, the selection is collapsed to the end point and moved up. If wdExtend is used, the selection is extended up. The default value is wdMove.</param>
    1062         /// <returns></returns>
    1063         public int MoveUp(object unit, object count, object extend)
    1064         {
    1065             return app.Selection.MoveUp(ref unit, ref count, ref extend);
    1066         }
    1067 
    1068         /// <summary>
    1069         /// 向下移动一个字符
    1070         /// </summary>
    1071         public void MoveDown()
    1072         {
    1073             MoveDown(1);
    1074         }
    1075 
    1076         /// <summary>
    1077         /// 光标下移
    1078         /// Moves the selection down and returns the number of units it's been moved.
    1079         /// 参数说明详见MoveUp
    1080         /// </summary>
    1081         public void MoveDown(int num = 1)
    1082         {
    1083             object unit = WdUnits.wdCharacter;
    1084             object count = num;
    1085             object extend = WdMovementType.wdMove;
    1086             MoveDown(unit, count, extend);
    1087         }
    1088 
    1089         /// <summary>
    1090         /// 光标下移
    1091         /// Moves the selection down and returns the number of units it's been moved.
    1092         /// 参数说明详见MoveUp
    1093         /// </summary>
    1094         public int MoveDown(object unit, object count, object extend)
    1095         {
    1096             return app.Selection.MoveDown(ref unit, ref count, ref extend);
    1097         }
    1098 
    1099         /// <summary>
    1100         /// 光标左移
    1101         /// Moves the selection to the left and returns the number of units it's been moved.
    1102         /// 参数说明详见MoveUp
    1103         /// </summary>
    1104         public void MoveLeft(int num = 1)
    1105         {
    1106             object unit = WdUnits.wdCharacter;
    1107             object count = num;
    1108             MoveLeft(unit, count, missing);
    1109         }
    1110 
    1111         /// <summary>
    1112         /// 光标左移
    1113         /// Moves the selection to the left and returns the number of units it's been moved.
    1114         /// 参数说明详见MoveUp
    1115         /// </summary>
    1116         public int MoveLeft(object unit, object count, object extend)
    1117         {
    1118             return app.Selection.MoveLeft(ref unit, ref count, ref extend);
    1119         }
    1120 
    1121         /// <summary>
    1122         /// 向右移动N个字符
    1123         /// </summary>
    1124         /// <param name="num"></param>
    1125         public void MoveRight(int num = 1)
    1126         {
    1127             object unit = WdUnits.wdCharacter;
    1128             object count = num;
    1129             MoveRight(unit, count, missing);
    1130         }
    1131 
    1132         /// <summary>
    1133         /// 光标右移
    1134         /// Moves the selection to the left and returns the number of units it's been moved.
    1135         /// 参数说明详见MoveUp
    1136         /// </summary>
    1137         public int MoveRight(object unit, object count, object extend)
    1138         {
    1139             return app.Selection.MoveRight(ref unit, ref count, ref extend);
    1140         }
    1141 
    1142         #endregion 光标位置
    1143 
    1144         #region 书签操作
    1145 
    1146         public void WriteIntoDocument(string bookmarkName, string context)
    1147         {
    1148             try
    1149             {
    1150                 object _bookmarkName = bookmarkName;
    1151                 Bookmark bm = doc.Bookmarks.get_Item(ref _bookmarkName); //返回书签
    1152                 if (bm != null)
    1153                 {
    1154                     bm.Range.Text = context; //设置书签域的内容
    1155                 }
    1156             }
    1157             catch (Exception exception)
    1158             {
    1159                 return;
    1160             }
    1161         }
    1162 
    1163         /// <summary>
    1164         /// 插入书签
    1165         /// 如过存在同名书签,则先删除再插入
    1166         /// </summary>
    1167         /// <param name="bookMarkName">书签名</param>
    1168         public void InsertBookMark(string bookMarkName)
    1169         {
    1170             //存在则先删除
    1171             if (doc.Bookmarks.Exists(bookMarkName))
    1172             {
    1173                 DeleteBookMark(bookMarkName);
    1174             }
    1175             object range = app.Selection.Range;
    1176             doc.Bookmarks.Add(bookMarkName, ref range);
    1177         }
    1178 
    1179         /// <summary>
    1180         /// 删除书签
    1181         /// </summary>
    1182         /// <param name="bookMarkName">书签名</param>
    1183         public void DeleteBookMark(string bookMarkName)
    1184         {
    1185             if (doc.Bookmarks.Exists(bookMarkName))
    1186             {
    1187                 var bookMarks = doc.Bookmarks;
    1188                 for (int i = 1; i <= bookMarks.Count; i++)
    1189                 {
    1190                     object index = i;
    1191                     var bookMark = bookMarks.get_Item(ref index);
    1192                     if (bookMark.Name == bookMarkName)
    1193                     {
    1194                         bookMark.Delete();
    1195                         break;
    1196                     }
    1197                 }
    1198             }
    1199         }
    1200 
    1201         /// <summary>
    1202         /// 删除所有书签
    1203         /// </summary>
    1204         public void DeleteAllBookMark()
    1205         {
    1206             for (; doc.Bookmarks.Count > 0;)
    1207             {
    1208                 object index = doc.Bookmarks.Count;
    1209                 var bookmark = doc.Bookmarks.get_Item(ref index);
    1210                 bookmark.Delete();
    1211             }
    1212         }
    1213 
    1214         /// <summary>
    1215         /// 替换书签内容
    1216         /// </summary>
    1217         /// <param name="bookMarkName">书签名</param>
    1218         /// <param name="text">替换后的内容</param>
    1219         public void ReplaceBookMark(string bookMarkName, string text)
    1220         {
    1221             bool isExist = GoToBookMark(bookMarkName);
    1222             if (isExist)
    1223             {
    1224                 InsertText(text);
    1225             }
    1226         }
    1227 
    1228         /// <summary>
    1229         /// 在书签中插入文本
    1230         /// </summary>
    1231         /// <param name="sBMName">书签名</param>
    1232         /// <param name="sBMValue">文本内容</param>
    1233         public void ReplaceBookMarkWithString(string sBMName, string sBMValue)
    1234         {
    1235             object oBmkName = sBMName;
    1236             if (doc.Bookmarks.Exists(sBMName))
    1237             {
    1238                 doc.Bookmarks.get_Item(ref oBmkName).Select();
    1239                 doc.Bookmarks.get_Item(ref oBmkName).Range.Text = sBMValue;
    1240             }
    1241         }
    1242 
    1243         /// <summary>
    1244         /// 在书签中插入图片
    1245         /// </summary>
    1246         /// <param name="bookmarkName">书签名</param>
    1247         /// <param name="imagePath">图片路径</param>
    1248         public void ReplaceBookMarkWithImage(string bookmarkName, string imagePath)
    1249         {
    1250             object oBmkName = bookmarkName;
    1251 
    1252             if (doc.Bookmarks.Exists(bookmarkName) && File.Exists(imagePath))
    1253             {
    1254                 object LinkToFile = false;
    1255                 object SaveWithDocument = true;
    1256                 doc.Bookmarks.get_Item(ref oBmkName).Select();
    1257                 app.Selection.InlineShapes.AddPicture(imagePath, ref LinkToFile, ref SaveWithDocument, ref missing);
    1258             }
    1259         }
    1260 
    1261         /// <summary>
    1262         /// 在书签中插入指定宽高的图片
    1263         /// </summary>
    1264         /// <param name="bookmarkName">书签名</param>
    1265         /// <param name="imagePath">图片路径</param>
    1266         /// <param name="Width">图片宽度</param>
    1267         /// <param name="Height">图片高度</param>
    1268         public void ReplaceBookMarkWithImage(string bookmarkName, string imagePath, int Width, int Height)
    1269         {
    1270             object oBmkName = bookmarkName;
    1271 
    1272             //读取源图片尺寸
    1273             Image picImage = Image.FromFile(imagePath);
    1274             int sourcePicWidth = picImage.Width;
    1275             int sourcePicHeight = picImage.Height;
    1276             double widthHeightRatio = (double)sourcePicWidth / (double)sourcePicHeight;
    1277             double heightWidthRatio = (double)sourcePicHeight / (double)sourcePicWidth;
    1278 
    1279             //计算插入文档后图片尺寸
    1280             int picWidth = Width;
    1281             int picHeight = Height;
    1282 
    1283             //根据图片原始宽高比得出缩放后的尺寸
    1284             if (picWidth > (int)picHeight * widthHeightRatio)
    1285             {
    1286                 picWidth = (int)(picHeight * widthHeightRatio);
    1287             }
    1288             else
    1289             {
    1290                 picHeight = (int)(picWidth * heightWidthRatio);
    1291             }
    1292 
    1293             if (doc.Bookmarks.Exists(bookmarkName) && File.Exists(imagePath))
    1294             {
    1295                 object LinkToFile = false;
    1296                 object SaveWithDocument = true;
    1297                 doc.Bookmarks.get_Item(ref oBmkName).Select();
    1298                 InlineShape inlineShape = app.Selection.InlineShapes.AddPicture(imagePath, ref LinkToFile, ref SaveWithDocument, ref missing);
    1299                 inlineShape.Width = picWidth;
    1300                 inlineShape.Height = picHeight;
    1301             }
    1302         }
    1303 
    1304         #endregion 书签操作
    1305 
    1306         #region 文件操作
    1307 
    1308         /// <summary>
    1309         /// 把Word文档装化为Html文件
    1310         /// </summary>
    1311         /// <param name="strFileName">要转换的Word文档</param>
    1312         /// <param name="strSaveFileName">要生成的具体的Html页面</param>
    1313         public bool WordToHtml(string strFileNameForWord, string strSaveFileName)
    1314         {
    1315             bool result = false;
    1316             try
    1317             {
    1318                 Type wordType = app.GetType();
    1319                 // 打开文件
    1320                 Type docsType = app.Documents.GetType();
    1321                 // 转换格式,另存为
    1322                 Type docType = doc.GetType();
    1323                 object saveFileName = strSaveFileName;
    1324                 docType.InvokeMember("SaveAs", System.Reflection.BindingFlags.InvokeMethod, null, doc, new object[] { saveFileName, WdSaveFormat.wdFormatHTML });
    1325 
    1326                 #region 其它格式:
    1327 
    1328                 ///wdFormatHTML
    1329                 ///wdFormatDocument
    1330                 ///wdFormatDOSText
    1331                 ///wdFormatDOSTextLineBreaks
    1332                 ///wdFormatEncodedText
    1333                 ///wdFormatRTF
    1334                 ///wdFormatTemplate
    1335                 ///wdFormatText
    1336                 ///wdFormatTextLineBreaks
    1337                 ///wdFormatUnicodeText
    1338                 //-----------------------------------------------------------------------------------
    1339                 //            docType.InvokeMember( "SaveAs", System.Reflection.BindingFlags.InvokeMethod,
    1340                 //                null, oDoc, new object[]{saveFileName, Word.WdSaveFormat.wdFormatHTML} );
    1341                 // 退出 Word
    1342                 //wordType.InvokeMember( "Quit", System.Reflection.BindingFlags.InvokeMethod,
    1343                 //    null, oWordApplic, null );
    1344 
    1345                 #endregion 其它格式:
    1346 
    1347                 result = true;
    1348             }
    1349             catch
    1350             {
    1351                 //throw ( new Exception() );
    1352             }
    1353             return result;
    1354         }
    1355 
    1356         /// <summary>
    1357         /// 保存当前项目
    1358         /// </summary>
    1359         public void SaveDocument()
    1360         {
    1361             if (app == null)
    1362                 throw new Exception("Create / Open Document first!");
    1363             if (doc == null)
    1364                 throw new Exception("Create / Open Document first!");
    1365             if (!doc.Saved)
    1366                 doc.Save();
    1367         }
    1368 
    1369         /// <summary>
    1370         /// 项目另存为
    1371         /// </summary>
    1372         public void SaveAsDocument(object path)
    1373         {
    1374             if (app == null)
    1375                 throw new Exception("Create / Open Document first!");
    1376             if (doc == null)
    1377                 throw new Exception("Create / Open Document first!");
    1378             doc.SaveAs(ref path, ref missing, ref missing, ref missing, ref missing, ref missing,
    1379                        ref missing, ref missing, ref missing, ref missing, ref missing,
    1380                        ref missing, ref missing, ref missing, ref missing, ref missing);
    1381         }
    1382 
    1383         /// <summary>
    1384         /// 关闭项目
    1385         /// </summary>
    1386         public void CloseDocument()
    1387         {
    1388             if (doc != null)
    1389             {
    1390                 try
    1391                 {
    1392                     object doNotSaveChanges = WdSaveOptions.wdDoNotSaveChanges;
    1393                     doc.Close(ref doNotSaveChanges, ref missing, ref missing);
    1394                 }
    1395                 catch
    1396                 {
    1397                     //Already Close
    1398                 }
    1399             }
    1400             if (app != null)
    1401             {
    1402                 try
    1403                 {
    1404                     object doNotSaveChanges = WdSaveOptions.wdDoNotSaveChanges;
    1405                     app.Documents.Close(ref doNotSaveChanges, ref missing, ref missing);
    1406                 }
    1407                 catch
    1408                 {
    1409                     //Already Close
    1410                 }
    1411             }
    1412             GC.Collect();
    1413             GC.WaitForPendingFinalizers();
    1414         }
    1415 
    1416         /// <summary>
    1417         /// 退出文档
    1418         /// </summary>
    1419         public void ExitDocument()
    1420         {
    1421             if (doc != null)
    1422             {
    1423                 try
    1424                 {
    1425                     doc.Close(ref missing, ref missing, ref missing);
    1426                 }
    1427                 catch (Exception)
    1428                 {
    1429                     throw;
    1430                 }
    1431             }
    1432 
    1433             app.Quit();
    1434             if (app != null)
    1435             {
    1436                 app = null;
    1437             }
    1438             GC.Collect();
    1439             GC.WaitForPendingFinalizers();
    1440         }
    1441 
    1442         #endregion 文件操作
    1443 
    1444         #region 资源回收
    1445 
    1446         private bool disposed = false;
    1447 
    1448         ~WordHelper()
    1449         {
    1450             //必须为false
    1451             Dispose(false);
    1452         }
    1453 
    1454         public void Dispose()
    1455         {
    1456             //必须为true
    1457             Dispose(true);
    1458             //通知垃圾回收机制不再调用终结器(析构器)
    1459             GC.SuppressFinalize(this);
    1460         }
    1461 
    1462         private void Dispose(bool disposing)
    1463         {
    1464             if (disposed)
    1465             {
    1466                 return;
    1467             }
    1468             if (disposing)
    1469             {
    1470                 // 清理托管资源
    1471             }
    1472 
    1473             if (doc != null)
    1474             {
    1475                 try
    1476                 {
    1477                     object doNotSaveChanges = WdSaveOptions.wdDoNotSaveChanges;
    1478                     doc.Close(ref doNotSaveChanges, ref missing, ref missing);
    1479                 }
    1480                 catch
    1481                 {
    1482                     //Already Close
    1483                 }
    1484             }
    1485             if (app != null)
    1486             {
    1487                 try
    1488                 {
    1489                     object doNotSaveChanges = WdSaveOptions.wdDoNotSaveChanges;
    1490                     app.Documents.Close(ref doNotSaveChanges, ref missing, ref missing);
    1491                 }
    1492                 catch
    1493                 {
    1494                     //Already Close
    1495                 }
    1496             }
    1497 
    1498             //System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
    1499             GC.Collect();
    1500             GC.WaitForPendingFinalizers();
    1501 
    1502             //让类型知道自己已经被释放
    1503             disposed = true;
    1504         }
    1505 
    1506         #endregion 资源回收
    1507 
    1508         #region 文档合并
    1509 
    1510         /// <summary>
    1511         /// 合并多个Word文档
    1512         /// </summary>
    1513         /// <param name="docPaths"></param>
    1514         /// <param name="output"></param>
    1515         public void InsertDocuments(List<string> docPaths, string bookmark)
    1516         {
    1517             object objIsWordVisible = false;
    1518             object doNotSaveChanges = WdSaveOptions.wdDoNotSaveChanges;
    1519             Document outDoc = doc;  // 插入到已经打开的文档
    1520             foreach (string item in docPaths)
    1521             {
    1522                 object fileName = item;
    1523                 Document partDoc = app.Documents.Open(
    1524           ref fileName, //FileName
    1525           ref missing, //ConfirmVersions
    1526           ref missing, //ReadOnly
    1527           ref missing, //AddToRecentFiles
    1528           ref missing, //PasswordDocument
    1529           ref missing, //PasswordTemplate
    1530           ref missing, //Revert
    1531           ref missing, //WritePasswordDocument
    1532           ref missing, //WritePasswordTemplate
    1533           ref missing, //Format
    1534           ref missing, //Enconding
    1535           ref objIsWordVisible, //Visible
    1536           ref missing, //OpenAndRepair
    1537           ref missing, //DocumentDirection
    1538           ref missing, //NoEncodingDialog
    1539           ref missing //XMLTransform
    1540           );
    1541                 partDoc.Activate();
    1542                 app.Selection.WholeStory();
    1543                 app.Selection.Copy();
    1544 
    1545                 outDoc.Activate();
    1546                 GoToBookMark(bookmark);
    1547                 app.Selection.Paste();
    1548 
    1549                 partDoc.Close(ref doNotSaveChanges, ref missing, ref missing);
    1550             }
    1551         }
    1552 
    1553         /// <summary>
    1554         /// 合并多个Word文档
    1555         /// </summary>
    1556         /// <param name="docPaths"></param>
    1557         /// <param name="output"></param>
    1558         public void MergeDocuments(List<string> docPaths, string output)
    1559         {
    1560             object objIsWordVisible = false;
    1561             object doNotSaveChanges = WdSaveOptions.wdDoNotSaveChanges;
    1562 
    1563             object outPath = output;
    1564             Document outDoc = app.Documents.Open(
    1565       ref outPath, //FileName
    1566       ref missing, //ConfirmVersions
    1567       ref missing, //ReadOnly
    1568       ref missing, //AddToRecentFiles
    1569       ref missing, //PasswordDocument
    1570       ref missing, //PasswordTemplate
    1571       ref missing, //Revert
    1572       ref missing, //WritePasswordDocument
    1573       ref missing, //WritePasswordTemplate
    1574       ref missing, //Format
    1575       ref missing, //Enconding
    1576       ref objIsWordVisible, //Visible
    1577       ref missing, //OpenAndRepair
    1578       ref missing, //DocumentDirection
    1579       ref missing, //NoEncodingDialog
    1580       ref missing //XMLTransform
    1581       );
    1582 
    1583             foreach (string item in docPaths)
    1584             {
    1585                 object fileName = item;
    1586                 Document partDoc = app.Documents.Open(
    1587           ref fileName, //FileName
    1588           ref missing, //ConfirmVersions
    1589           ref missing, //ReadOnly
    1590           ref missing, //AddToRecentFiles
    1591           ref missing, //PasswordDocument
    1592           ref missing, //PasswordTemplate
    1593           ref missing, //Revert
    1594           ref missing, //WritePasswordDocument
    1595           ref missing, //WritePasswordTemplate
    1596           ref missing, //Format
    1597           ref missing, //Enconding
    1598           ref objIsWordVisible, //Visible
    1599           ref missing, //OpenAndRepair
    1600           ref missing, //DocumentDirection
    1601           ref missing, //NoEncodingDialog
    1602           ref missing //XMLTransform
    1603           );
    1604                 partDoc.Activate();
    1605                 app.Selection.WholeStory();
    1606                 app.Selection.Copy();
    1607 
    1608                 outDoc.Activate();
    1609                 MoveToBottom();
    1610                 app.Selection.Paste();
    1611 
    1612                 partDoc.Close(ref doNotSaveChanges, ref missing, ref missing);
    1613             }
    1614 
    1615             object path = output;
    1616             outDoc.SaveAs(ref path, ref missing, ref missing, ref missing, ref missing, ref missing,
    1617                        ref missing, ref missing, ref missing, ref missing, ref missing,
    1618                        ref missing, ref missing, ref missing, ref missing, ref missing);
    1619 
    1620             outDoc.Close(ref doNotSaveChanges, ref missing, ref missing);
    1621         }
    1622 
    1623         #endregion 文档合并
    1624 
    1625         #region 页面设置
    1626 
    1627         //设置页眉
    1628         public void SetHeader(string titleText)
    1629         {
    1630             app.ActiveWindow.ActivePane.View.SeekView = WdSeekView.wdSeekCurrentPageHeader;
    1631             app.Selection.WholeStory();
    1632             app.Selection.TypeText(titleText);
    1633             app.ActiveWindow.ActivePane.View.SeekView = WdSeekView.wdSeekMainDocument;
    1634         }
    1635 
    1636         //修改页眉 -
    1637         public bool ReplacePageHeader(string oldtext, string newtext, int tbcount)
    1638         {
    1639             try
    1640             {
    1641                 Range range;
    1642                 for (int i = 1; i <= tbcount; i++)
    1643                 {
    1644                     range = doc.Sections[i].Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
    1645                     bool sig = range.Find.Execute(oldtext,
    1646                             ref missing,
    1647                             ref missing,
    1648                             ref missing,
    1649                             ref missing,
    1650                             ref missing,
    1651                             ref missing,
    1652                             ref missing,
    1653                             ref missing,
    1654                              newtext,
    1655                              WdReplace.wdReplaceAll,
    1656                             ref missing,
    1657                             ref missing,
    1658                             ref missing,
    1659                             ref missing);
    1660                 }
    1661                 return true;
    1662             }
    1663             catch (Exception ex)
    1664             {
    1665                 Console.WriteLine(ex.Message);
    1666                 return false;
    1667             }
    1668         }
    1669 
    1670         //页面设置
    1671         public void SetPage(Orientation orientation, double width, double height, double topMargin, double leftMargin, double rightMargin, double bottomMargin)
    1672         {
    1673             doc.PageSetup.PageWidth = app.CentimetersToPoints((float)width);
    1674             doc.PageSetup.PageHeight = app.CentimetersToPoints((float)height);
    1675 
    1676             if (orientation == Orientation.横板)
    1677             {
    1678                 doc.PageSetup.Orientation = WdOrientation.wdOrientLandscape;
    1679             }
    1680 
    1681             doc.PageSetup.TopMargin = (float)(topMargin * 25);//上边距
    1682             doc.PageSetup.LeftMargin = (float)(leftMargin * 25);//左边距
    1683             doc.PageSetup.RightMargin = (float)(rightMargin * 25);//右边距
    1684             doc.PageSetup.BottomMargin = (float)(bottomMargin * 25);//下边距
    1685         }
    1686 
    1687         public void SetPage(Orientation orientation, double topMargin, double leftMargin, double rightMargin, double bottomMargin)
    1688         {
    1689             SetPage(orientation, 21, 29.7, topMargin, leftMargin, rightMargin, bottomMargin);
    1690         }
    1691 
    1692         public void SetPage(double topMargin, double leftMargin, double rightMargin, double bottomMargin)
    1693         {
    1694             SetPage(Orientation.竖板, 21, 29.7, topMargin, leftMargin, rightMargin, bottomMargin);
    1695         }
    1696 
    1697         //插入页脚 -
    1698         public bool InsertPageFooter(string text, System.Drawing.Font font, Alignment alignment)
    1699         {
    1700             try
    1701             {
    1702                 app.ActiveWindow.View.SeekView = WdSeekView.wdSeekCurrentPageFooter;//页脚
    1703                 app.Selection.InsertAfter(text);
    1704                 GetWordFont(app.Selection.Font, font);
    1705 
    1706                 SetAlignment(app.Selection.Range, alignment);
    1707 
    1708                 return true;
    1709             }
    1710             catch (Exception)
    1711             {
    1712                 return false;
    1713             }
    1714         }
    1715 
    1716         public bool InsertPageFooterNumber(System.Drawing.Font font, Alignment alignment)
    1717         {
    1718             try
    1719             {
    1720                 app.ActiveWindow.View.SeekView = WdSeekView.wdSeekCurrentPageHeader;
    1721                 app.Selection.WholeStory();
    1722                 app.Selection.ParagraphFormat.Borders[WdBorderType.wdBorderBottom].LineStyle = WdLineStyle.wdLineStyleNone;
    1723                 app.ActiveWindow.View.SeekView = WdSeekView.wdSeekMainDocument;
    1724 
    1725                 app.ActiveWindow.View.SeekView = WdSeekView.wdSeekCurrentPageFooter;//页脚
    1726                 app.Selection.TypeText("");
    1727 
    1728                 object page = WdFieldType.wdFieldPage;
    1729                 app.Selection.Fields.Add(app.Selection.Range, ref page, ref missing, ref missing);
    1730 
    1731                 app.Selection.TypeText("页/共");
    1732                 object pages = WdFieldType.wdFieldNumPages;
    1733 
    1734                 app.Selection.Fields.Add(app.Selection.Range, ref pages, ref missing, ref missing);
    1735                 app.Selection.TypeText("");
    1736 
    1737                 GetWordFont(app.Selection.Font, font);
    1738                 SetAlignment(app.Selection.Range, alignment);
    1739                 app.ActiveWindow.View.SeekView = WdSeekView.wdSeekMainDocument;
    1740                 return true;
    1741             }
    1742             catch (Exception)
    1743             {
    1744                 return false;
    1745             }
    1746         }
    1747 
    1748         //修改页脚
    1749         public bool ReplacePageFooter(string oldtext, string newtext, int tbcount)
    1750         {
    1751             try
    1752             {
    1753                 Range range;
    1754                 for (int i = 1; i <= tbcount; i++)
    1755                 {
    1756                     range = doc.Sections[i].Footers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
    1757                     bool sig = range.Find.Execute(oldtext,
    1758                                 ref missing,
    1759                                 ref missing,
    1760                                 ref missing,
    1761                                 ref missing,
    1762                                 ref missing,
    1763                                 ref missing,
    1764                                 ref missing,
    1765                                 ref missing,
    1766                                 newtext,
    1767                                 WdReplace.wdReplaceAll,
    1768                                 ref missing,
    1769                                 ref missing,
    1770                                 ref missing,
    1771                                 ref missing);
    1772                 }
    1773                 return true;
    1774             }
    1775             catch (Exception ex)
    1776             {
    1777                 Console.WriteLine(ex.Message);
    1778                 return false;
    1779             }
    1780         }
    1781 
    1782         #endregion 页面设置
    1783 
    1784         #region 常用方法
    1785 
    1786         /// <summary>
    1787         /// 给表头排序
    1788         /// </summary>
    1789         /// <param name="tableNo"></param>
    1790         /// <param name="no"></param>
    1791         /// <returns></returns>
    1792         public bool TableTitleNumberOrder(string tableNo, int no)
    1793         {
    1794             bool findover = false;
    1795             Selection currentselect = app.Selection;//实例化一个selection接口
    1796             currentselect.Find.ClearFormatting();
    1797             currentselect.Find.Text = tableNo;//查询的文字
    1798             currentselect.Find.Wrap = WdFindWrap.wdFindStop;//查询完成后停止
    1799             findover = currentselect.Find.Execute(ref missing, ref missing,
    1800                           ref missing, ref missing,
    1801                           ref missing, ref missing,
    1802                           ref missing, ref missing,
    1803                           ref missing, ref missing,
    1804                           ref missing, ref missing,
    1805                           ref missing, ref missing,
    1806                           ref missing);
    1807 
    1808             currentselect.Expand(WdUnits.wdParagraph); //扩展选区到整行
    1809             string oldWord = Regex.Match(currentselect.Range.Text, tableNo + @".d+", RegexOptions.IgnoreCase).Value;
    1810             string newWord = tableNo + "." + no.ToString();
    1811             Replace(oldWord, newWord, currentselect.Range);
    1812             currentselect.MoveDown(WdUnits.wdParagraph, 1);
    1813             return findover;
    1814         }
    1815 
    1816         //获取Word中的颜色 -
    1817         public WdColor GetWordColor(Color c)
    1818         {
    1819             UInt32 R = 0x1, G = 0x100, B = 0x10000;
    1820             return (WdColor)(R * c.R + G * c.G + B * c.B);
    1821         }
    1822 
    1823         #endregion 常用方法
    1824 
    1825         public enum Orientation
    1826         {
    1827             横板,
    1828             竖板
    1829         }
    1830 
    1831         public enum Alignment
    1832         {
    1833             左对齐,
    1834             居中,
    1835             右对齐
    1836         }
    1837     }
    1838 }
  • 相关阅读:
    atom 安装插件列表
    django学习
    windows 安装 python3
    python3 监控代码变化 自动重启 提高开发效率
    git无法pull仓库refusing to merge unrelated histories
    python 项目部署virtualenv
    python 多线程并发threading & 任务队列Queue
    python logging 日志使用
    jupyter 教程
    mysql 替换数据库字段内容
  • 原文地址:https://www.cnblogs.com/maruko/p/5015770.html
Copyright © 2020-2023  润新知