C#代码操作/编辑Word的基础知识

来源:互联网 发布:房地产数据网 编辑:程序博客网 时间:2024/05/22 00:18
在用代码编辑word文档内容的前提工作前需要先声明一个命名空间:Using.Microsoft.Office.Interop.Word;
需要导入的组件是:Microsoft Office 11.0 Object Library;

必须实例化的两个类:
Microsoft.Office.Interop.Word.Application   myword = new  Microsoft.Office.Interop.Word.Application();//对word软件进行操作。

Microsoft.Office.Interop.Word.Documnent   mydocumnent  =  new  Microsoft.Office.Interop.Word.Documnent();//对word软件中的文本操作

必要功能用到的实例化类:
Microsoft.Office.Interop.Word.Rand   myrand  =  myword.Selection.Range;//对word软件中的中文字体设置的操作

Microsoft.Office.Interop.Word.InlineShape  shape = myword.ActiveWindow.ActivePane.Selection.InlineShapes.AddPicture("图片地址",Nothing,Nothing,Nothing);//页眉插入图片

Microsoft.Office.Interop.Word.PageNumbers  Pns  = myword.Selection.Sections[1].Headers[WdHeaderFooterIndex.wdHeaderFooterEvenPages].PageNumbers;//获取当前页码

下面代码用到的变量:
适用COM库,因此有许多变量需要用System.Reflection.Missing.Value代替
Object Nothing = System.Reflection.Missing.Value;//选参数的默认参数Object unite = WdUnits.wdStory;//word场景

代码很长很长....................long.............可以直接复制直接使用学习!

1、页面设置、页眉图片和文字设置,最后跳出页眉设置
    /*页面设置*/            mydoc.PageSetup.PaperSize = WdPaperSize.wdPaperA4;//页面A4纸            mydoc.PageSetup.Orientation = WdOrientation.wdOrientPortrait;//排列方式            mydoc.PageSetup.TopMargin = 57.0f;//页面顶部            mydoc.PageSetup.BottomMargin = 57.0f;//页面底部            mydoc.PageSetup.LeftMargin = 57.0f;//左边距            mydoc.PageSetup.RightMargin = 57.0f;//右边距            mydoc.PageSetup.HeaderDistance = 30.0f;//页眉和顶部之间的位置            /*设置页眉*/            myword.ActiveWindow.View.Type = WdViewType.wdNormalView;//普通视图(即页面视图)样式            myword.ActiveWindow.View.SeekView = WdSeekView.wdSeekPrimaryHeader;//进入页眉设置            myword.Selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight;//页眉中的文字右对齐                        //插入页眉图片            myword.Selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;//页面中心对齐            string imagepath = @"C:\Users\Administrator\Desktop\桌面程序\mmexport1489334036325.jpg";            //Microsoft.Office.Interop.Word.InlineShape shape1 = myword.ActiveWindow.ActivePane.Selection.InlineShapes.AddPicture(imagepath, Nothing, Nothing, Nothing);//插入页眉            myword.ActiveWindow.ActivePane.Selection.InsertAfter("文档页眉");            //去掉页眉的横线            myword.ActiveWindow.ActivePane.Selection.ParagraphFormat.Borders[WdBorderType.wdBorderBottom].LineStyle = WdLineStyle.wdLineStyleNone;            myword.ActiveWindow.ActivePane.Selection.Borders[WdBorderType.wdBorderBottom].Visible = false;            myword.ActiveWindow.ActivePane.View.SeekView = WdSeekView.wdSeekMainDocument;//退出页眉设置            #region 页码设置并添加页码            //页眉和页尾的页码            PageNumbers pns = myword.Selection.Sections[1].Headers[WdHeaderFooterIndex.wdHeaderFooterEvenPages].PageNumbers;//获取当前页的号码            pns.NumberStyle = WdPageNumberStyle.wdPageNumberStyleNumberInDash;//设置页码的风格,是Dash形还是圆形的            pns.HeadingLevelForChapter = 0;//标题等级            pns.IncludeChapterNumber = false;//章节号是否“包含页码或标题标签”。            pns.RestartNumberingAtSection = false;//页编号是否“指定节的开始处再次出现”            pns.StartingNumber = 0;//开始页页码            object pagenmbetal = WdPageNumberAlignment.wdAlignPageNumberCenter;//将号码设置在中间            object first = true;            myword.Selection.Sections[1].Footers[WdHeaderFooterIndex.wdHeaderFooterEvenPages].PageNumbers.Add(ref pagenmbetal, ref first);            #endregion
2、行间距与缩进、文本字体、字号、加粗、斜体、颜色、下划线、下划线颜色设置
            myword.Selection.ParagraphFormat.LineSpacing = 16f;//设置文档的行间距            myword.Selection.ParagraphFormat.FirstLineIndent = 30;//首行缩进的长度            //写入普通文本            strContent = "我是普通文本\n";            mydoc.Paragraphs.Last.Range.Text = strContent;            mydoc.Paragraphs.Last.Range.Text = "我在加一行试试,这里不加'\\n'";            //直接添加段,不会覆盖(+=)            mydoc.Paragraphs.Last.Range.Text += "不会覆盖的";            //添加在此段的文字后面,不是新段落            mydoc.Paragraphs.Last.Range.InsertAfter("不用换行,直接接上去上面的内容");            //将文档的前四个字,替换成“替换字体”,并设置成红色字体            object start = 0;//起始字符            object end = 4;//结束字符            Range rang = mydoc.Range(ref start, ref end);            rang.Font.Color = WdColor.wdColorRed;//设置红色字体            rang.Text = "替换字体";            myword.Application.Selection.ParagraphFormat.FirstLineIndent = 0;//取消首行缩进的长度            //写入黑体文本            myword.Application.Selection.EndKey(ref unite, ref Nothing);//光标移到文本末尾            strContent = "这是黑体文本\n";            mydoc.Paragraphs.Last.Range.Font.Name = "黑体";            mydoc.Paragraphs.Last.Range.Text = strContent;            //写入加粗文本            strContent = "这是粗体文本\n";            myword.Selection.EndKey(ref unite, ref Nothing);//光标移到文本末尾            mydoc.Paragraphs.Last.Range.Font.Bold = 1;//加粗            mydoc.Paragraphs.Last.Range.Text = strContent;            //写入15号字体文本            strContent = "我是15号文本\n";            myword.Selection.EndKey(ref unite, ref Nothing);//光标移到文本末尾            mydoc.Paragraphs.Last.Range.Font.Size = 15;//大小            mydoc.Paragraphs.Last.Range.Font.Name = "宋体";            mydoc.Paragraphs.Last.Range.Text = strContent;            //写入斜体文本            strContent = "我是斜体字文本\n";            myword.Selection.EndKey(ref unite, ref Nothing);//光标移到文本末尾            mydoc.Paragraphs.Last.Range.Font.Italic = 1;//斜体            mydoc.Paragraphs.Last.Range.Text = strContent;            //写入蓝色文本            strContent = "我是蓝色的文本\n";            myword.Selection.EndKey(ref unite, ref Nothing);//光标移到文本末尾            mydoc.Paragraphs.Last.Range.Font.Color = WdColor.wdColorBlue;//字体为蓝色            mydoc.Paragraphs.Last.Range.Text = strContent;            //写入下划线文本            strContent = "我是下划线文本\n";            myword.Selection.EndKey(ref unite, ref Nothing);//光标移到文本末尾            mydoc.Paragraphs.Last.Range.Font.Underline = WdUnderline.wdUnderlineThick;//下划线文本            mydoc.Paragraphs.Last.Range.Text = strContent;            //写入红色下画线文本            strContent = "我是点线下划线,并且下划线是红色的\n";            myword.Selection.EndKey(ref unite, ref Nothing);//光标移到文本末尾            mydoc.Paragraphs.Last.Range.Font.Underline = WdUnderline.wdUnderlineDottedHeavy;//设置点下划线            mydoc.Paragraphs.Last.Range.Font.UnderlineColor = WdColor.wdColorRed;//设置下划线为红色            mydoc.Paragraphs.Last.Range.Text = strContent;            //取消下划线,并且将字号调整为12号            strContent = "取消下划线,并且设置字号为12号,黑色不要斜体\n";            myword.Selection.EndKey(ref unite, ref Nothing);//光标移到文本末尾            mydoc.Paragraphs.Last.Range.Font.Size = 12;//字体大小            mydoc.Paragraphs.Last.Range.Font.Underline = WdUnderline.wdUnderlineNone;//取消下划线            mydoc.Paragraphs.Last.Range.Font.Color = WdColor.wdColorBlue;//设置黑色字体            mydoc.Paragraphs.Last.Range.Font.Italic = 0;//关闭斜体            mydoc.Paragraphs.Last.Range.Text = strContent;
在用C#编辑Word过程中,经常用到myword.Selection.Paragraphs.Last.Text = "插入文本,默认的文本光标不会移到最后一个字符上,这时候需要用myword.Selection.EndKey(ref unite,ref  NoThing),此函数意思是把光标移到最后一行,下面是测试代码:"。
      #region 中途学习测试            if (false)            {                myword.Selection.ParagraphFormat.FirstLineIndent = 1;//首行缩进                myword.Selection.Paragraphs.Last.Range.Font.Bold = 15;//字体加粗                myword.Selection.Paragraphs.Last.Range.Text = "你好!!!";                myword.Selection.EndKey(ref unite, ref Nothing);//如果没有这行 文本添加会被替代。                myword.Application.Selection.TypeParagraph();//插入空白行                mydoc.Paragraphs.Last.Range.Font.Size = 30;                mydoc.Paragraphs.Last.Range.Font.Color = WdColor.wdColorRed;                mydoc.Paragraphs.Last.Range.Text = "你不好!!!";            }            #endregion
3、插入图片、居中显示、设置图片的绝对尺寸和缩放尺寸,并给图片添加标题
myword.Selection.EndKey(ref unite, ref Nothing);            //图片文件的路径            string filename = @"C:\Users\小蔡\Desktop\软件\mmexport1489334036325.jpg";            //要向Word文档中插入图片的位置            object range = mydoc.Paragraphs.Last.Range;            //定义该插入的图片是否为外部链接            object linkToFile = false;            //定义要插入的图片是否随Word文档一起保存            object saveWithDocument = true;            //使用哪种形式插入图片(这里使用嵌入式)            mydoc.InlineShapes.AddPicture(filename, linkToFile, saveWithDocument, range);//插入图片            mydoc.InlineShapes.AddPictureBullet(filename, range);/*(插入相同的图片)在文档中添加一个图片,该图片为AppPicture所指向的对象图片*/            mydoc.InlineShapes.AddPicture(filename, null, null, range);//功能效果等同于mydoc.InlineShapes.AddPicture(filename,linkToFlie,saveWithDocument,range);*/            myword.Selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;//居中显示图片            //设置图片宽高的绝对大小            mydoc.InlineShapes[1].Width = 500;//宽            mydoc.InlineShapes[1].Height = 200;//高            //按比例缩放大小            mydoc.InlineShapes[1].ScaleWidth = 50;            mydoc.InlineShapes[1].ScaleHeight = 100;            //图片下方居中添加图片标题            myword.Selection.EndKey(ref unite, ref Nothing);            /*mydoc.Paragraphs.Last.Range.Text = "\n";//指定文本,且需要输入的内容*/            mydoc.Content.InsertAfter("\n");//插入文本的结尾            myword.Selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;//段落居中            mydoc.Paragraphs.Last.Range.Font.Size = 10;//字体大小            mydoc.Paragraphs.Last.Range.Text = "测试图片01";            #endregion

4、添加表格,填充数据,设置表格行列宽高,合并单元格,添加表头斜线,给单元格添加图片
            myword.Selection.EndKey(ref unite, ref Nothing);            myword.Selection.TypeParagraph();            myword.Selection.TypeParagraph();            myword.Selection.TypeParagraph();            object tableBehavior = WdDefaultTableBehavior.wdWord9TableBehavior;//自动调整            object autoFitBehavior = WdAutoFitBehavior.wdAutoFitWindow;//不调整表格大小            myword.Selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft;//段落对齐方式            //第一个表            mydoc.Tables.Add(mydoc.Paragraphs.Last.Range, 10, 2, tableBehavior, autoFitBehavior);//插入表格,第一个表格            //第二个表            myword.Selection.EndKey(ref unite, ref Nothing);//光标移至末尾            mydoc.Content.InsertAfter("\n");//末尾换行            myword.Selection.TypeParagraph();//插入一行的空白行            mydoc.Tables.Add(mydoc.Paragraphs.Last.Range, 10, 2, Nothing, Nothing);//插入表格,第二个表格            //第三个表            myword.Selection.EndKey(ref unite, ref Nothing);//word程序文档移至结尾            myword.Selection.Document.Content.InsertAfter("\n");//word文档换行处理            myword.Selection.TypeParagraph();//添加一行空白行            Table table = myword.Selection.Tables.Add(myword.Selection.Range, 5, 3, Nothing, Nothing);//添加表格并且把表格赋值给table            table.Borders.Enable = 1;//设置表格有边框            //添加表格数据            mydoc.Tables[3].Cell(1, 1).Range.Text = "列\n行";            int sum = 1;            for (int i = 1; i <= mydoc.Tables[3].Rows.Count; i++)            {                for (int j = 1; j <= mydoc.Tables[3].Columns.Count; j++)                {                    mydoc.Tables[3].Cell(i, j).Range.Text = sum.ToString();                    sum++;                }            }            //新添加一行            mydoc.Tables[3].Rows.Add(ref Nothing);            mydoc.Tables[3].Rows[6].Height = 50;//设置新增加的这行表格的高度            //向新添加的行的单元格中添加图片            string FileName = @"C:\Users\小蔡\Desktop\软件\mmexport1489334036325.jpg";            object LinkToFile = false;            object SaveWithDocument = true;            object Anchor = table.Cell(6, 3).Range;//选中要添加图片的单元格            myword.ActiveDocument.InlineShapes.AddPicture(FileName, ref linkToFile, ref SaveWithDocument, ref Anchor);//第四参数为:选中要输入的位置            mydoc.InlineShapes.AddPicture(FileName, ref linkToFile, ref SaveWithDocument, mydoc.Tables[3].Cell(6, 2).Range);//同上            mydoc.InlineShapes[2].Width = 50;//图片宽度            mydoc.InlineShapes[2].Height = 35;//图片高度            mydoc.InlineShapes[3].Width = 50;//图片宽度            mydoc.InlineShapes[3].Height = 35;//图片高度            //设置图片为四周坏绕型            Shape s = mydoc.InlineShapes[2].ConvertToShape();//指定图片转换类型形式            s.WrapFormat.Type = WdWrapType.wdWrapSquare;//四周环绕            //s.WrapFormat.Type = WdWrapType.wdWrapBehind;//文字下面            //s.WrapFormat.Type = WdWrapType.wdWrapFront;//文字上方            //s.WrapFormat.Type = WdWrapType.wdWrapInline;//嵌入式            //s.WrapFormat.Type = WdWrapType.wdWrapNone;//无格式            //s.WrapFormat.Type = WdWrapType.wdWrapThrough;//穿越型环绕            //s.WrapFormat.Type = WdWrapType.wdWrapTight;//紧密型环绕            //s.WrapFormat.Type = WdWrapType.wdWrapTopBottom;//上下型环绕            //设置table样式            //设置table样式            table.Rows.HeightRule = WdRowHeightRule.wdRowHeightAtLeast;//行的高度            table.Rows.Height = myword.CentimetersToPoints(float.Parse("0.8"));            table.Range.Font.Size = 10.5F;//表格文字            table.Range.Font.Bold = 20;//加粗            table.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;//表格文本居中            table.Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalBottom;//文本垂直贴到底部            //设置table边框样式            table.Borders.OutsideLineStyle = WdLineStyle.wdLineStyleDouble;//表格外框是双线            table.Borders.InsideLineStyle = WdLineStyle.wdLineStyleSingle;//表格内框是单线            table.Rows[1].Range.Font.Bold = 1;//加粗            table.Rows[1].Range.Font.Size = 12F;            table.Cell(1, 1).Range.Font.Size = 10.5F;            myword.Selection.Cells.Height = 30;//所有单元格的高度            //除第一行外,其他行的行高都设置为20            for (int i = 2; i <= mydoc.Tables[3].Rows.Count; i++)            {                mydoc.Tables[3].Rows[i].Height = 20;            }            /*表2左上角输入行和列*/            //设置第一行高度30,其他行高度20            //设置行居右,设置列居左            mydoc.Tables[2].Rows[1].Height = 30;            mydoc.Tables[2].Borders.Enable = 1;            for (int i = 2; i <= mydoc.Tables[2].Rows.Count; i++)            {                mydoc.Tables[2].Rows[i].Height = 20;            }            mydoc.Tables[2].Cell(1, 1).Range.Text = "行\n列";            //表格左上角的单元格里的文字(居右)            mydoc.Tables[2].Cell(1, 1).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight;            //表格左上角的单元格里的列字(居左)            mydoc.Tables[2].Cell(1, 1).Range.Paragraphs[2].Alignment = WdParagraphAlignment.wdAlignParagraphLeft;            //第一列设置宽度50,其他列设置75            mydoc.Tables[2].Columns[1].Width = 50;            for (int i = 2; i < mydoc.Tables[2].Columns.Count; i++)            {                mydoc.Tables[2].Columns[i].Width = 75;            }            mydoc.Tables[2].Rows[2].Cells[1].Range.Text = "序号1";            mydoc.Tables[2].Columns[1].Cells[3].Range.Text = "序号2";            mydoc.Tables[2].Cell(4, 1).Range.Text = "序号3";            mydoc.Tables[2].Cell(4, 1).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight;            mydoc.Tables[2].Cell(4, 1).Width = 100;            mydoc.Tables[2].Cell(4, 1).Height = 50;            //添加表头斜线,并设置表头的样式            mydoc.Tables[2].Cell(1, 1).Borders[WdBorderType.wdBorderDiagonalDown].Visible = true;            /*对表2的第一行第一列的单元格进行设置,单元格对角边界设置画一条直线wdBorderDiagonalDown*/            mydoc.Tables[2].Cell(1, 1).Borders[WdBorderType.wdBorderDiagonalDown].Color = WdColor.wdColorRed;//对边的颜色设置            mydoc.Tables[2].Cell(1, 1).Borders[WdBorderType.wdBorderDiagonalDown].LineWidth = WdLineWidth.wdLineWidth150pt;//对边的边界厚度            //mydoc.Tables[2].Columns[2].Width = 100;            mydoc.Tables[2].Cell(2, 1).Borders[WdBorderType.wdBorderBottom].Visible = true;//底部分界            mydoc.Tables[2].Cell(2, 2).Borders[WdBorderType.wdBorderDiagonalDown].Visible = true;//做上角开始的对角线            //mydoc.Tables[2].Cell(2, 3).Borders[WdBorderType.wdBorderDiagonalUp].Visible = true;//运行异常,HRESULT E_FAIL 未指定的失败 0x80004005            //mydoc.Tables[2].Cell(2, 4).Borders[WdBorderType.wdBorderHorizontal].Visible = true;//运行异常,HRESULT E_FAIL 未指定的失败 0x80004005            //mydoc.Tables[2].Cell(2, 5).Borders[WdBorderType.wdBorderLeft].Visible = true;//水平分界            /*合并单元格*/            mydoc.Tables[2].Cell(3, 1).Merge(mydoc.Tables[2].Cell(3, 2));//横向合并            mydoc.Tables[2].Cell(5, 1).Merge(mydoc.Tables[2].Cell(10, 2));//多行合并            #endregion            myword.Selection.EndKey(ref unite, ref Nothing);            mydoc.Content.InsertAfter("\n换行结尾符");
5、编辑Word结束后保存为.docx文件
            /* ++多种保存格式的保存格式++ */            object format003 = WdSaveFormat.wdFormatDocument;//word2003的保存格式            object format007 = WdSaveFormat.wdFormatDocumentDefault;//word2007的保存格式            object format97 = WdSaveFormat.wdFormatDocument97;//word97的保存格式            object formatText1 = WdSaveFormat.wdFormatDOSText;//文本格式            object formatText2 = WdSaveFormat.wdFormatDOSTextLineBreaks;//文本格式保存换行符版            object formatcode = WdSaveFormat.wdFormatEncodedText;//编码文本格式            object formatHTML1 = WdSaveFormat.wdFormatFilteredHTML;//过滤HTML格式            object formatXML = WdSaveFormat.wdFormatFlatXML;//内部使用保留            object formatHTML2 = WdSaveFormat.wdFormatHTML;//标准HTML格式            object formatPDF = WdSaveFormat.wdFormatPDF;//PDF格式            //等等还有很多其他种存储格式            /* ++保存为DOCX文件++*/            if (true)            {                //此方法对应于“保存为”对话框(文件菜单)中的选项。                mydoc.SaveAs(ref path, ref format007,                    ref Nothing, ref Nothing, ref Nothing,                    ref Nothing, ref Nothing, ref Nothing,                    ref Nothing, ref Nothing, ref Nothing,                    ref Nothing, ref Nothing, ref Nothing,                    ref Nothing, ref Nothing                    );            }            if (false)            {                //此方法的一些参数对应于“保存”对话框(文件选项卡)中的选项。 只适用在Word2010项目中。                mydoc.SaveAs2(ref  path,                    ref Nothing, ref Nothing, ref Nothing,                    ref Nothing, ref Nothing, ref Nothing,                    ref Nothing, ref Nothing, ref Nothing,                    ref Nothing);            }            if (false)            {   mydoc.SaveAs(); }

其中mydoc.SaveAs(..)和mydoc.SaveAs2(..)的区别在于SaveAs2只适用在Word2010项目中。
6、打印编辑完成的文档
 DialogResult dr = MessageBox.Show("打印提示框", "是否继续打印", MessageBoxButtons.YesNo, MessageBoxIcon.None);            if (dr == System.Windows.Forms.DialogResult.Yes)            {                mydoc.PrintOut();            }
7、关闭AppLication和Documnent的使用
            mydoc.Close(ref Nothing,ref Nothing,ref Nothing);            myword.Quit(ref Nothing,ref Nothing ,ref Nothing);

我把wordCOM库中常用的属性和方法进行归类,方便以后查找。有需要的道友可以评论留下私人邮箱。




原创粉丝点击