欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

比较全的一个C#操作word文档示例

程序员文章站 2023-11-06 21:44:46
最近两天研究了一下如何使用vs2008(c#语言)输出word文档。以下是几点总结: 1、非常简单。 2、开发及运行环境要求。操作系统为:windowsxp(安装.ne...

最近两天研究了一下如何使用vs2008(c#语言)输出word文档。以下是几点总结:

1、非常简单。

2、开发及运行环境要求。操作系统为:windowsxp(安装.net framework2.0)/vista/win7;在操作系统必须安装word2003完全安装版。这里必须要强调是word2003完全安装版,因为软件开发及运行都需要一个com组件:microsoft word 11.0 object library。如果不是word2003完全安装版,可以下载这个com组件,并手动的安装这个com组件。下载地址为:,文件不大,只有4m左右。

3、c#工程设置。这里的工程设置,就是添加com组件。步骤为:在工程资源管理器中"添加引用"->"com"选项卡->在下拉列表中选microsoft word 11.0 object library。ok了,看上去,跟添加一般的dll一样,但实际上vs2008在这个过程中完成一系列复杂的关于.net调用com组件的操作,不过,幸好我们不用管这个。

4、接下就是写代码了。在这里,使用word的com对像,跟使用一般的非com对像一样,非常流畅,好像根本就不管它什么com不com的。为了使代码比较简洁,可以在源代码文件顶添加这样的一条语句:using word = microsoft.office.interop.word;

5、最好是对word对像模型有一定的了解,这样在写代码的时候就不会那么“迷茫”了。wore对像模型中有几个比较重要的对像,它们是application、document、selection、range、bookmark,以及其它的一些对像,如:paragraph、section、table等级。刚开始学的时候,感觉selection、range、bookmark这几个对像有点迷惑人,selection可能好理解,就是表示当前的选择区域,如果没有选择就表示光标所在位置。range和bookmark,其实在很多地方很像,不过也有一些区别,在这里就不多说了,google一下"word.range"就行了。

6、在写代码的过程中,经常会想要实现的一些操作,但是由于对word对像不熟悉而不知怎么用代码实现。比如设置页眉、添加页码什么的,如果在word程序里手动的操作当然很简单,但是要用代码来实现,对初学者来说就可能不那么容易了。遇到这种情况,一般有两种方法可以选择:一种是"百度/google法",别一种,也是我所推荐的一种就是,利用word的“录制宏”功能把想要实现的操作录成宏之后,再看宏里的代码,宏里的代码其实几乎就是你想要的代码了(只不过语法有一点不一样而已)。

7、以下给出一个示例,这个示例里面包括了一些常用的图、文、表、公式的编辑与排版以及页面设置、页眉、页码的操作,里面都有注释,写得很清楚。

using system;
using system.collections.generic;
using system.componentmodel;
using system.data;
using system.drawing;
using system.text;
using microsoft.office.interop;
using word = microsoft.office.interop.word;
using system.runtime.interopservices; 

namespace windowsformsapplication1
{
  public partial class form1 :system.windows.forms. form
  {

    [dllimport("shell32.dll ")]
    public static extern int shellexecute(intptr hwnd, string lpszop, string lpszfile, string lpszparams, string lpszdir, int fsshowcmd); 
    public form1()
    {
      initializecomponent();
    }

    private void button1_click(object sender, eventargs e)
    {
      //新建文档
      // word.application newapp = new word.application();//用这句也能初始化
      word.application newapp = new word.applicationclass();
      word.document newdoc;
      object nothing=system.reflection.missing.value;//用于作为函数的默认参数
      newdoc = newapp.documents.add(ref nothing, ref nothing, ref nothing, ref nothing);//生成一个word文档
      newapp.visible = true ;//是否显示word程序界面

      //页面设置
      //newdoc.pagesetup.orientation = word.wdorientation.wdorientlandscape ;
      //newdoc.pagesetup.pagewidth = newapp.centimeterstopoints(21.0f);
      //newdoc.pagesetup.pageheight = newapp.centimeterstopoints(29.7f);
      newdoc.pagesetup.papersize = word.wdpapersize.wdpapera4;
      newdoc.pagesetup.orientation = word.wdorientation.wdorientportrait;
      newdoc.pagesetup.topmargin = 57.0f;
      newdoc.pagesetup.bottommargin = 57.0f;
      newdoc.pagesetup.leftmargin = 57.0f;
      newdoc.pagesetup.rightmargin = 57.0f;
      newdoc.pagesetup.headerdistance = 30.0f;//页眉位置

      //设置页眉
      newapp.activewindow.view.type = word.wdviewtype.wdoutlineview;//视图样式。
      newapp.activewindow.view.seekview = word.wdseekview.wdseekprimaryheader;//进入页眉设置,其中页眉边距在页面设置中已完成
      newapp.selection.paragraphformat.alignment = word.wdparagraphalignment.wdalignparagraphright;
      //插入页眉图片
      string headerfile = "d:\\header.jpg";
      this.outpicture(headerfile, properties.resources.header);
      word.inlineshape shape1= newapp.activewindow.activepane.selection.inlineshapes.addpicture(headerfile, ref nothing, ref nothing, ref nothing);
      shape1.height = 30;
      shape1.width = 80;
      newapp.activewindow.activepane.selection.insertafter("中建东北院");
      //去掉页眉的那条横线
      newapp.activewindow.activepane.selection.paragraphformat.borders[microsoft.office.interop.word.wdbordertype.wdborderbottom].linestyle = word.wdlinestyle.wdlinestylenone;
      newapp.activewindow.activepane.selection.borders[microsoft.office.interop.word.wdbordertype.wdborderbottom].visible = false;
      newapp.activewindow.activepane.view.seekview = word.wdseekview.wdseekmaindocument;//退出页眉设置

      //添加页码
      word.pagenumbers pns= newapp.selection.sections[1].headers[microsoft.office.interop.word.wdheaderfooterindex.wdheaderfooterevenpages].pagenumbers;
      pns.numberstyle = word.wdpagenumberstyle.wdpagenumberstylenumberindash;
      pns.headinglevelforchapter = 0;
      pns.includechapternumber = false;
      pns.chapterpageseparator = word.wdseparatortype.wdseparatorhyphen;
      pns.restartnumberingatsection = false;
      pns.startingnumber = 0;
      object pagenmbetal=word.wdpagenumberalignment.wdalignpagenumbercenter;
      object first=true; 
      newapp.selection.sections[1].footers[microsoft.office.interop.word.wdheaderfooterindex.wdheaderfooterevenpages ].pagenumbers.add(ref pagenmbetal, ref first);

      //文字设置(selection表示当前选择集,如果当前没有选择对像,则指对光标所在处进行设置)
      newapp.selection.font.size = 14;
      newapp.selection.font.bold = 0;
      newapp.selection.font.color = word.wdcolor.wdcolorblack;
      newapp.selection.font.name = "宋体";

      //段落设置
      newapp.selection.paragraphformat.linespacingrule = word.wdlinespacing.wdlinespaceexactly;
      newapp.selection.paragraphformat.linespacing = 20;
      newapp.selection.paragraphformat.alignment = word.wdparagraphalignment.wdalignparagraphleft;
      newapp.selection.paragraphformat.firstlineindent = 30;
      newdoc.content.insertafter( windowsformsapplication1.properties.resources.previewwords);
      
      

      //插入公式
      object oendofdoc="\\endofdoc";
      word.range rang1 = newdoc.bookmarks.get_item(ref oendofdoc).range;
      object fieldtype = word.wdfieldtype.wdfieldempty;
      object formula = @"eq \i(a,b,ξxdx)";
      object presrveformatting = false;
      rang1.text = formula.tostring();
      rang1.font.size = 14;
      rang1.font.bold = 0;
      rang1.font.subscript = 0;
      rang1.font.color = word.wdcolor.wdcolorblue;
      rang1.font.name = "宋体";
      rang1.paragraphformat.linespacingrule = word.wdlinespacing.wdlinespacesingle;
      rang1.paragraphformat.alignment = word.wdparagraphalignment.wdalignparagraphright;
      newdoc.fields.add(rang1, ref fieldtype, ref formula, ref presrveformatting);

      //将文档的前三个字替换成"asdfasdf",并将其颜色设为蓝色
      object start=0;
      object end=3;
      word.range rang2 = newdoc.range(ref start, ref end);
      rang2.font.color = word.wdcolor.wdcolorblue;
      rang2.text = "as签";

      //将文档开头的"as"替换成"袁波"
      rang1.start = 0;
      rang1.end = 2;
      rang1.text = "这是一个";
      rang1.insertafter("书");
      //rang1.select();
      object codirection = word.wdcollapsedirection.wdcollapsestart;
      rang1.collapse(ref codirection);//将rang1的起点和终点都定于起点或终点

      //对前三个字符进行加粗
      newdoc.range(ref start, ref end).bold = 1;
      object rang = rang2;
      newdoc.bookmarks.add("yb",ref rang);
      
      
      object unite = word.wdunits.wdstory;
      newapp.selection.endkey(ref unite, ref nothing);//将光标移至文末
      newapp.selection.font.size = 10;
      newapp.selection.typetext("...............................(式1)\n");


      //插入图片
      newapp.selection.endkey(ref unite, ref nothing);//将光标移至文末
      //newapp.selection.homekey(ref unite, ref nothing);//将光标移至文开头
      newapp.selection.paragraphformat.linespacingrule = word.wdlinespacing.wdlinespacesingle;
      newapp.selection.paragraphformat.alignment = word.wdparagraphalignment.wdalignparagraphcenter;
      object linktofile = false;
      object savewithdocument = true;
      object anchor = newapp.selection.range;
      string picname = "d:\\kk.jpg";
      this.outpicture(picname, properties.resources.img_2169);
      newdoc.inlineshapes.addpicture(picname, ref linktofile, ref savewithdocument, ref anchor);
      newdoc.inlineshapes[1].height = 200;
      newdoc.inlineshapes[1].width = 200;
      newdoc.content.insertafter("\n");
      newapp.selection.endkey(ref unite, ref nothing);//将光标移至文末
      newapp.selection.paragraphformat.alignment = word.wdparagraphalignment.wdalignparagraphcenter;
      newapp.selection.font.size = 10;
      newapp.selection.typetext("图1 袁冶\n");
      newapp.selection.paragraphformat.alignment = word.wdparagraphalignment.wdalignparagraphright;
      newdoc.content.insertafter("\n"); 
      newdoc.content.insertafter("\n");

      //用这种方式也可以插入公式,并且这种方法更简单
      newapp.selection.font.size = 14;
      newapp.selection.insertformula(ref formula, ref nothing);
      newapp.selection.font.size = 10;
      newapp.selection.typetext("..............................(式2)\n");
      newapp.selection.paragraphformat.alignment = word.wdparagraphalignment.wdalignparagraphcenter;
      newapp.selection.typetext("表1 电子产品\n");

      //插入表格
      word.table table1 = newdoc.tables.add(newapp.selection.range, 4, 3, ref nothing, ref nothing);
      newdoc.tables[1].cell(1, 1).range.text = "产品\n项目";
      newdoc.tables[1].cell(1, 2).range.text = "电脑";
      newdoc.tables[1].cell(1, 3).range.text = "手机";
      newdoc.tables[1].cell(2, 1).range.text = "重量(kg)";
      newdoc.tables[1].cell(3, 1).range.text = "价格(元)";
      newdoc.tables[1].cell(4, 1).range.text = "共同信息";
      newdoc.tables[1].cell(4, 2).range.text = "信息a";
      newdoc.tables[1].cell(4,3).range.text = "信息b";
      

      table1.select();
      table1.rows.alignment = word.wdrowalignment.wdalignrowcenter;//整个表格居中
      newapp.selection.cells.verticalalignment = word.wdcellverticalalignment.wdcellalignverticalcenter;
      newapp.selection.paragraphformat.alignment = word.wdparagraphalignment.wdalignparagraphcenter;
      newapp.selection.cells.heightrule = word.wdrowheightrule.wdrowheightexactly;
      newapp.selection.cells.height = 40;
      table1.rows[2].height = 20;
      table1.rows[3].height = 20;
      table1.rows[4].height = 20;
      table1.range.paragraphformat.alignment = word.wdparagraphalignment.wdalignparagraphcenter;
      newapp.selection.cells.width=150;
      table1.columns[1].width = 75;
      table1.cell(1, 1).range.paragraphformat.alignment = word.wdparagraphalignment.wdalignparagraphright;
      table1.cell(1, 1).range.paragraphs[2].format.alignment = word.wdparagraphalignment.wdalignparagraphleft;

      
      

      //表头斜线
      table1.cell(1, 1).borders[microsoft.office.interop.word.wdbordertype.wdborderdiagonaldown ].visible = true;
      table1.cell(1, 1).borders[microsoft.office.interop.word.wdbordertype.wdborderdiagonaldown].color = word.wdcolor.wdcolorgreen;
      table1.cell(1, 1).borders[microsoft.office.interop.word.wdbordertype.wdborderdiagonaldown].linewidth = word.wdlinewidth.wdlinewidth050pt;

      //表格边框
      table1.borders[microsoft.office.interop.word.wdbordertype.wdborderhorizontal ].visible = true;
      table1.borders[microsoft.office.interop.word.wdbordertype.wdborderhorizontal].color = word.wdcolor.wdcolorgreen;
      table1.borders[microsoft.office.interop.word.wdbordertype.wdborderhorizontal].linewidth = word.wdlinewidth.wdlinewidth050pt;

      table1.borders[microsoft.office.interop.word.wdbordertype.wdbordervertical].visible = true;
      table1.borders[microsoft.office.interop.word.wdbordertype.wdbordervertical].color = word.wdcolor.wdcolorgreen;
      table1.borders[microsoft.office.interop.word.wdbordertype.wdbordervertical].linewidth = word.wdlinewidth.wdlinewidth050pt;

      table1.borders[microsoft.office.interop.word.wdbordertype.wdborderleft].visible = true;
      table1.borders[microsoft.office.interop.word.wdbordertype.wdborderleft].color = word.wdcolor.wdcolorgreen;
      table1.borders[microsoft.office.interop.word.wdbordertype.wdborderleft].linewidth = word.wdlinewidth.wdlinewidth050pt;
      table1.borders[microsoft.office.interop.word.wdbordertype.wdborderleft].linestyle = word.wdlinestyle.wdlinestyledoublewavy;

      table1.borders[microsoft.office.interop.word.wdbordertype.wdborderright].visible = true;
      table1.borders[microsoft.office.interop.word.wdbordertype.wdborderright].color = word.wdcolor.wdcolorgreen;
      table1.borders[microsoft.office.interop.word.wdbordertype.wdborderright].linewidth = word.wdlinewidth.wdlinewidth050pt;
      table1.borders[microsoft.office.interop.word.wdbordertype.wdborderright].linestyle = word.wdlinestyle.wdlinestyledoublewavy;

      table1.borders[microsoft.office.interop.word.wdbordertype.wdborderbottom ].visible = true;
      table1.borders[microsoft.office.interop.word.wdbordertype.wdborderbottom].color = word.wdcolor.wdcolorgreen;
      table1.borders[microsoft.office.interop.word.wdbordertype.wdborderbottom].linewidth = word.wdlinewidth.wdlinewidth050pt;
      table1.borders[microsoft.office.interop.word.wdbordertype.wdborderbottom].linestyle = word.wdlinestyle.wdlinestyledouble;

      table1.borders[microsoft.office.interop.word.wdbordertype.wdbordertop ].visible = true;
      table1.borders[microsoft.office.interop.word.wdbordertype.wdbordertop].color = word.wdcolor.wdcolorgreen;
      table1.borders[microsoft.office.interop.word.wdbordertype.wdbordertop].linewidth = word.wdlinewidth.wdlinewidth050pt;
      table1.borders[microsoft.office.interop.word.wdbordertype.wdbordertop].linestyle = word.wdlinestyle.wdlinestyledouble;

      //合并单元格
      newdoc.tables[1].cell(4, 2).merge(table1.cell(4, 3));

      //删除图片
      this.delpictfile(headerfile);
      this.delpictfile(picname);


      //保存文档
      object name = "c:\\yb3.doc";
      newdoc.saveas(ref name, 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, ref nothing);
      
      //关闭文档
      object saveoption = word.wdsaveoptions.wddonotsavechanges;
      newdoc.close(ref nothing , ref nothing, ref nothing);
      newapp.application.quit(ref saveoption, ref nothing, ref nothing);
      newdoc = null;
      newapp = null;
      shellexecute(intptr.zero, "open", "c:\\yb3.doc", "", "", 3);
    }

    private void outpicture(string filename,system.drawing.bitmap bmap)
    {
      bmap.save(filename);
    }

    private void delpictfile(string filename)
    {
      system.io.file.delete(filename);
    }
   
  }

}