C# 操作Word

来源:互联网 发布:java电商网站源码下载 编辑:程序博客网 时间:2024/06/07 10:33

近段在做个关于操作Word的项目,现在项目中用到相关Word操作代码整理如下:

 

一、启动和关闭退出

     

           Microsoft.Office.Interop.Word.Application thisApplication = null;

                object MissingValue = Type.Missing;

                try

                {

                    thisApplication = new Microsoft.Office.Interop.Word.ApplicationClass();

                }

                catch (Exception ex)

                {

                    return;

                }

                finally

                {

                    if (thisApplication!= null)

                    {

                        thisApplication.Quit(ref MissingValue, ref MissingValue, ref MissingValue);

                        Marshal.ReleaseComObject(thisApplication);

                        thisApplication = null;

                        GC.Collect();

                        GC.WaitForPendingFinalizers();

                    }

                }

 

 

二、打开文件

 

                object otargetFileName = targetFileName;

                Document thisDocument = thisApplication.Documents.Open(ref otargetFileName, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue);

 

三、保存并关闭

 

thisDocument.Save();

                if (thisDocument != null)

                    thisDocument.Close(ref MissingValue, ref MissingValue, ref MissingValue);

 

四、另存为

 

          public void SaveAs(string filePath)

          {

           object dummy=System.Reflection.Missing.Value;

               object obj=filePath;

         document.SaveAs( ref obj,ref dummy,ref dummy,ref dummy,ref dummy,ref dummy,ref dummy,ref dummy,ref dummy,ref dummy,ref dummy);

          }

 

五、遍利书签,并在指定书签位输入文本

 

                for (int i = 1; i <= thisDocument.Bookmarks.Count; i++)

                {

                    object index = i;

                    Bookmark bm = thisDocument.Bookmarks.get_Item(ref index);

                    string bm_name = bm.Name;

                    bm.Select();

thisDocument.Application.Selection.TypeText("test");

                }

 

六、查找指定书签,并取得书签包含的第一个表格

 

            object bm_name = "G_人员参于情况表";

            Bookmark bm_grid = thisDocument.Bookmarks.get_Item(ref bm_name);

            if (bm_grid != null)

            {

                bm_grid.Select();

                Table maintable = thisDocument.Application.Selection.Tables[1];

            }

七、表格相关操作

 

maintable.Cell(1, 1).Range.Text = “姓名”; //第一行第一列输入姓名

maintable.Rows.Add(ref MissingValue); //添加新行

 

八、复制粘贴

 

         bm_templet.Select();

thisDocument.Application.Selection.Copy();

         Bookmark chuzhang_end = thisDocument.Bookmarks.get_Item(ref bm_chuzhang_end);

chuzhang_end.Select();

thisDocument.Application.Selection.Paste();

 

九、插入分页

 

        public void WordInsertBreakPage(Document thisDocument)

        {

            if (thisDocument.Application.Selection != null)

            {

                object o = WdBreakType.wdPageBreak;

                thisDocument.Application.Selection.InsertBreak(ref o);

            }

   }

 

十、回车换行

 

thisDocument.Application.Selection.TypeParagraph();

 

十一、上下左右移动光标位

 

private void moveLeft()

{         

              object moveUnit = Microsoft.Office.Interop.Word.WdUnits.wdWord;

              object moveCount = 1;

              object moveExtend = Microsoft.Office.Interop.Word.WdMovementType.wdExtend;

              thisDocument.Application.Selection.MoveLeft(ref moveUnit, ref moveCount, ref MissingValue);

}

          private void moveRight()

          {

               if(selection==null||selection!=document.Application.Selection)

                    selection=document.Application.Selection;    

                object dummy=System.Reflection.Missing.Value;

                object count=1;          

                object Unit=Word.WdUnits.wdCharacter;

                selection.MoveRight(ref Unit,ref count,ref dummy);

          }

 

十二、取得当前光标位

 

          public void GetCursor()

          {

               if(selection==null||selection!=document.Application.Selection)

                 selection=document.Application.Selection;

                object a=selection.get_Information(Word.WdInformation.wdFirstCharacterLineNumber);

               object b=selection.get_Information(Word.WdInformation.wdFirstCharacterColumnNumber);

               object c=selection.get_Information(Word.WdInformation.wdActiveEndAdjustedPageNumber);

               MessageBox.Show(a.ToString()+"行,"+b.ToString()+"列,"+c.ToString()+"页");

          }

 

十三、定位到指定行或相对行

 

          /// <summary>

          /// 定位到指定行

          /// </summary>

          /// <param name="lineNum">行号</param>

          private void gotoAbsolutLine(int lineNum)

          {

              if(selection==null||selection!=document.Application.Selection)

                selection=document.Application.Selection;

               object dummy=System.Reflection.Missing.Value;

               object what=Word.WdGoToItem.wdGoToLine;

               object which=Word.WdGoToDirection.wdGoToFirst;

               object count=lineNum;

               selection.GoTo(ref what,ref which,ref count,ref dummy);

          }

          /// <summary>

          /// 定位到相对行,例如+4

          /// </summary>

          /// <param name="lineNum">行数</param>

          private void gotoOppositeLine(int lineNum)

          {

               if(selection==null||selection!=document.Application.Selection)

                 selection=document.Application.Selection;

               object dummy=System.Reflection.Missing.Value;

               object what=Word.WdGoToItem.wdGoToLine;

               object which;

               if(lineNum<0)

                 which=Word.WdGoToDirection.wdGoToPrevious;

               else

                    which=Word.WdGoToDirection.wdGoToNext;       

               object count=Math.Abs(lineNum);

               selection.GoTo(ref what,ref which,ref count,ref dummy);

          }

 

十四、定位到文档最后一行

 

        private void gotoLastLine(Document thisDocument)

        {

            object dummy = System.Reflection.Missing.Value;

            object what = WdGoToItem.wdGoToLine;

            object which = WdGoToDirection.wdGoToLast;

            object count = 99999999;

            thisDocument.Application.Selection.GoTo(ref what, ref which, ref count, ref dummy);

        }

 

 

十五、定位到第一个字符

 

          private void gotoFirstCharacter()

          {

               if(selection==null||selection!=document.Application.Selection)

                    selection=document.Application.Selection;                           

               int oldLine=0;

               gotoAbsolutLine(1);

               object a=selection.get_Information(Word.WdInformation.wdFirstCharacterLineNumber);//得到当前行号

               while(oldLine!=int.Parse(a.ToString()))//一直按右键,直到光标不再往下了为止

               {

                    oldLine++;

                    moveRight();

                    a=selection.get_Information(Word.WdInformation.wdFirstCharacterLineNumber);                               

               }

               gotoAbsolutLine(int.Parse(a.ToString()));

 

          }

 

十六、定位到最后一个字符

 

          public void gotoLastCharacter()

          {

               if(selection==null||selection!=document.Application.Selection)

                    selection=document.Application.Selection;

               gotoLastLine();

               object dummy=System.Reflection.Missing.Value;

               object count=99999999;         

               object Unit=Word.WdUnits.wdCharacter;

               selection.MoveRight(ref Unit,ref count,ref dummy);

          }

 

十七、       查找

 

          public bool WordFindString(string searchText,bool isTongpeifu)

          {

               try

               {

                    object dummy=System.Reflection.Missing.Value;

                    if(selection==null)

                        selection=document.Application.Selection;                      

                 object Unit=Word.WdUnits.wdLine;

                    //home

                    selection.HomeKey(ref Unit,ref dummy);

                    object thisTrue=true;

                    object findText=(object)searchText;

                    object replaceText=(object)"";//replacetext;

                    object thisContinue=Word.WdFindWrap.wdFindContinue;

                    object istpf=isTongpeifu;

                    //标记替换为空

                    selection.Find.Execute(ref findText,ref dummy,ref dummy,ref istpf,ref dummy,ref dummy,ref thisTrue,ref thisContinue,ref dummy,ref dummy,ref dummy,ref dummy,ref dummy,ref dummy,ref dummy);        

//                 MessageBox.Show(selection.Text);

                    return selection.Find.Found;

               }

               catch

               {

                    selection=document.Application.Selection;

                    object dummy=System.Reflection.Missing.Value;

                    object Unit=Word.WdUnits.wdLine;

                    //home

                    selection.HomeKey(ref Unit,ref dummy);

                    object thisTrue=true;

                    object findText=(object)searchText;

                    object replaceText=(object)"";//replacetext;

                    object thisContinue=Word.WdFindWrap.wdFindContinue;

                    object istpf=isTongpeifu;

                    //标记替换为空

                    selection.Find.Execute(ref findText,ref dummy,ref dummy,ref istpf,ref dummy,ref dummy,ref thisTrue,ref thisContinue,ref dummy,ref dummy,ref dummy,ref dummy,ref dummy,ref dummy,ref dummy);        

                    return selection.Find.Found;                 

               }

          }

 

十八、       查找替换

 

        public bool WordReplace(string findtext, string replacetext, bool isAll, Document document)

        {

            Selection selection = null;

            try

            {

                object dummy = System.Reflection.Missing.Value;

                selection = document.Application.Selection;

                object thisTrue = true;

                object findText = (object)findtext;

                object replaceText = (object)replacetext;

                object thisContinue = WdFindWrap.wdFindContinue;

                object all;

                if (isAll)

                    all = WdReplace.wdReplaceAll;

                else

                    all = dummy;

 

                selection.Find.Execute(ref findText, ref dummy, ref dummy, ref dummy, ref dummy, ref dummy, ref thisTrue, ref thisContinue, ref dummy, ref replaceText, ref all, ref dummy, ref dummy, ref dummy, ref dummy);

                return selection.Find.Found;

            }

            catch

            {

                selection = document.Application.Selection;

                object dummy = System.Reflection.Missing.Value;

                object thisTrue = true;

                object findText = (object)findtext;

                object replaceText = (object)replacetext;

                object thisContinue = WdFindWrap.wdFindContinue;

                object all;

                if (isAll)

                    all = WdReplace.wdReplaceAll;

                else

                    all = dummy;

 

                selection.Find.Execute(ref findText, ref dummy, ref dummy, ref dummy, ref dummy, ref dummy, ref thisTrue, ref thisContinue, ref dummy, ref replaceText, ref all, ref dummy, ref dummy, ref dummy, ref dummy);

                return selection.Find.Found;

 

            }

        }

 

十九、       插入图片

 

          public void WordInsertPhoto(string PhotoFilePath,int Width,int Height)

          {

               if (document.Application.Selection != null)

               {

                    object LinkToFile = false;

                    object SaveToDocument = true;

                    Word.InlineShape Shape;

                    object PhotoRange = System.Reflection.Missing.Value;

                    Shape = document.Application.Selection.InlineShapes.AddPicture(@PhotoFilePath,ref LinkToFile,ref SaveToDocument,ref PhotoRange);

                    if (Width != 0 || Height != 0)

                    {

                        Shape.Width = Width;

                        Shape.Height = Height;

                    }

               }

          }

 

二十、插入来自粘贴板的图片,并改变其大小

 

                        //向WORD中写入图片
                        bm_grid.Select();
                        thisDocument.Application.Selection.PasteAndFormat(WdRecoveryType.wdChartPicture);
                        //改变图片大小
                        object moveUnit = Microsoft.Office.Interop.Word.WdUnits.wdCharacter;
                        object moveCount = 1;
                        object moveExtend = Microsoft.Office.Interop.Word.WdMovementType.wdExtend;
                        thisDocument.Application.Selection.MoveLeft(ref moveUnit, ref moveCount, ref moveExtend);
                        if (System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width <= 1024)
                        {
                            thisDocument.Application.Selection.InlineShapes[1].Height = 240.55f;
                            thisDocument.Application.Selection.InlineShapes[1].Width = 500f;
                        }
                        else
                        {
                            thisDocument.Application.Selection.InlineShapes[1].Height = 260.55f;
                            thisDocument.Application.Selection.InlineShapes[1].Width = 535f;
                        }

 

二十一、       取得行、列、页信息

 

          public string WordGetRCP()

          {

                    selection=document.Application.Selection;//wd.Selection;

                    object a=selection.get_Information(Word.WdInformation.wdFirstCharacterLineNumber);

                    object b=selection.get_Information(Word.WdInformation.wdFirstCharacterColumnNumber);

                    object c=selection.get_Information(Word.WdInformation.wdActiveEndAdjustedPageNumber);

                    return a.ToString()+","+b.ToString()+","+c.ToString();

          }