最近两天研究了一下如何使用VS2008(C#语言)输出Word文档。以下是几点总结:
1、非常简单。
2、开发及运行环境要求。操作系统为:WindowsXP(安装.net framework2.0)/Vista/Win7;在操作系统必须安装Word2003完全安装版。这里必须要强调是Word2003完全安装版,因为软件开发及运行都需要一个com组件:Microsoft word 11.0 Object Library。如果不是Word2003完全安装版,可以下载这个com组件,并手动的安装这个com组件。下载地址为:http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=20923,文件不大,只有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、以下给出一个示例,这个示例里面包括了一些常用的图、文、表、公式的编辑与排版以及页面设置、页眉、页码的操作,里面都有注释,写得很清楚。
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Text; 7 using Microsoft.Office.Interop; 8 using Word = Microsoft.Office.Interop.Word; 9 using System.Runtime.InteropServices; 10 11 namespace WindowsFormsApplication1 12 { 13 public partial class Form1 :System.Windows.Forms. Form 14 { 15 16 [DllImport("shell32.dll ")] 17 public static extern int ShellExecute(IntPtr hwnd, String lpszOp, String lpszFile, String lpszParams, String lpszDir, int FsShowCmd); 18 public Form1() 19 { 20 InitializeComponent(); 21 } 22 23 private void button1_Click(object sender, EventArgs e) 24 { 25 //新建文档 26 // Word.Application newapp = new Word.Application();//用这句也能初始化 27 Word.Application newapp = new Word.ApplicationClass(); 28 Word.Document newdoc; 29 object nothing=System.Reflection.Missing.Value;//用于作为函数的默认参数 30 newdoc = newapp.Documents.Add(ref nothing, ref nothing, ref nothing, ref nothing);//生成一个word文档 31 newapp.Visible = true ;//是否显示word程序界面 32 33 //页面设置 34 //newdoc.PageSetup.Orientation = Word.WdOrientation.wdOrientLandscape ; 35 //newdoc.PageSetup.PageWidth = newapp.CentimetersToPoints(21.0f); 36 //newdoc.PageSetup.PageHeight = newapp.CentimetersToPoints(29.7f); 37 newdoc.PageSetup.PaperSize = Word.WdPaperSize.wdPaperA4; 38 newdoc.PageSetup.Orientation = Word.WdOrientation.wdOrientPortrait; 39 newdoc.PageSetup.TopMargin = 57.0f; 40 newdoc.PageSetup.BottomMargin = 57.0f; 41 newdoc.PageSetup.LeftMargin = 57.0f; 42 newdoc.PageSetup.RightMargin = 57.0f; 43 newdoc.PageSetup.HeaderDistance = 30.0f;//页眉位置 44 45 //设置页眉 46 newapp.ActiveWindow.View.Type = Word.WdViewType.wdOutlineView;//视图样式。 47 newapp.ActiveWindow.View.SeekView = Word.WdSeekView.wdSeekPrimaryHeader;//进入页眉设置,其中页眉边距在页面设置中已完成 48 newapp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight; 49 //插入页眉图片 50 string headerfile = "d:\\header.jpg"; 51 this.outpicture(headerfile, Properties.Resources.header); 52 Word.InlineShape shape1= newapp.ActiveWindow.ActivePane.Selection.InlineShapes.AddPicture(headerfile, ref nothing, ref nothing, ref nothing); 53 shape1.Height = 30; 54 shape1.Width = 80; 55 newapp.ActiveWindow.ActivePane.Selection.InsertAfter("中建东北院"); 56 //去掉页眉的那条横线 57 newapp.ActiveWindow.ActivePane.Selection.ParagraphFormat.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].LineStyle = Word.WdLineStyle.wdLineStyleNone; 58 newapp.ActiveWindow.ActivePane.Selection.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].Visible = false; 59 newapp.ActiveWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekMainDocument;//退出页眉设置 60 61 //添加页码 62 Word.PageNumbers pns= newapp.Selection.Sections[1].Headers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterEvenPages].PageNumbers; 63 pns.NumberStyle = Word.WdPageNumberStyle.wdPageNumberStyleNumberInDash; 64 pns.HeadingLevelForChapter = 0; 65 pns.IncludeChapterNumber = false; 66 pns.ChapterPageSeparator = Word.WdSeparatorType.wdSeparatorHyphen; 67 pns.RestartNumberingAtSection = false; 68 pns.StartingNumber = 0; 69 object pagenmbetal=Word.WdPageNumberAlignment.wdAlignPageNumberCenter; 70 object first=true; 71 newapp.Selection.Sections[1].Footers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterEvenPages ].PageNumbers.Add(ref pagenmbetal, ref first); 72 73 //文字设置(Selection表示当前选择集,如果当前没有选择对像,则指对光标所在处进行设置) 74 newapp.Selection.Font.Size = 14; 75 newapp.Selection.Font.Bold = 0; 76 newapp.Selection.Font.Color = Word.WdColor.wdColorBlack; 77 newapp.Selection.Font.Name = "宋体"; 78 79 //段落设置 80 newapp.Selection.ParagraphFormat.LineSpacingRule = Word.WdLineSpacing.wdLineSpaceExactly; 81 newapp.Selection.ParagraphFormat.LineSpacing = 20; 82 newapp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft; 83 newapp.Selection.ParagraphFormat.FirstLineIndent = 30; 84 newdoc.Content.InsertAfter( WindowsFormsApplication1.Properties.Resources.PreViewWords); 85 86 87 88 //插入公式 89 object oEndOfDoc="\\endofdoc"; 90 Word.Range rang1 = newdoc.Bookmarks.get_Item(ref oEndOfDoc).Range; 91 object fieldType = Word.WdFieldType.wdFieldEmpty; 92 object formula = @"eq \i(a,b,ξxdx)"; 93 object presrveFormatting = false; 94 rang1.Text = formula.ToString(); 95 rang1.Font.Size = 14; 96 rang1.Font.Bold = 0; 97 rang1.Font.Subscript = 0; 98 rang1.Font.Color = Word.WdColor.wdColorBlue; 99 rang1.Font.Name = "宋体";100 rang1.ParagraphFormat.LineSpacingRule = Word.WdLineSpacing.wdLineSpaceSingle;101 rang1.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;102 newdoc.Fields.Add(rang1, ref fieldType, ref formula, ref presrveFormatting);103 104 //将文档的前三个字替换成"asdfasdf",并将其颜色设为蓝色105 object start=0;106 object end=3;107 Word.Range rang2 = newdoc.Range(ref start, ref end);108 rang2.Font.Color = Word.WdColor.wdColorBlue;109 rang2.Text = "as签";110 111 //将文档开头的"as"替换成"袁波"112 rang1.Start = 0;113 rang1.End = 2;114 rang1.Text = "这是一个";115 rang1.InsertAfter("书");116 //rang1.Select();117 object codirection = Word.WdCollapseDirection.wdCollapseStart;118 rang1.Collapse(ref codirection);//将rang1的起点和终点都定于起点或终点119 120 //对前三个字符进行加粗121 newdoc.Range(ref start, ref end).Bold = 1;122 object rang = rang2;123 newdoc.Bookmarks.Add("yb",ref rang);124 125 126 object unite = Word.WdUnits.wdStory;127 newapp.Selection.EndKey(ref unite, ref nothing);//将光标移至文末128 newapp.Selection.Font.Size = 10;129 newapp.Selection.TypeText("...............................(式1)\n");130 131 132 //插入图片133 newapp.Selection.EndKey(ref unite, ref nothing);//将光标移至文末134 //newapp.Selection.HomeKey(ref unite, ref nothing);//将光标移至文开头135 newapp.Selection.ParagraphFormat.LineSpacingRule = Word.WdLineSpacing.wdLineSpaceSingle;136 newapp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;137 object LinkToFile = false;138 object SaveWithDocument = true;139 object Anchor = newapp.Selection.Range;140 string picname = "d:\\kk.jpg";141 this.outpicture(picname, Properties.Resources.IMG_2169);142 newdoc.InlineShapes.AddPicture(picname, ref LinkToFile, ref SaveWithDocument, ref Anchor);143 newdoc.InlineShapes[1].Height = 200;144 newdoc.InlineShapes[1].Width = 200;145 newdoc.Content.InsertAfter("\n");146 newapp.Selection.EndKey(ref unite, ref nothing);//将光标移至文末147 newapp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;148 newapp.Selection.Font.Size = 10;149 newapp.Selection.TypeText("图1 袁冶\n");150 newapp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;151 newdoc.Content.InsertAfter("\n"); 152 newdoc.Content.InsertAfter("\n");153 154 //用这种方式也可以插入公式,并且这种方法更简单155 newapp.Selection.Font.Size = 14;156 newapp.Selection.InsertFormula(ref formula, ref nothing);157 newapp.Selection.Font.Size = 10;158 newapp.Selection.TypeText("..............................(式2)\n");159 newapp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;160 newapp.Selection.TypeText("表1 电子产品\n");161 162 //插入表格163 Word.Table table1 = newdoc.Tables.Add(newapp.Selection.Range, 4, 3, ref nothing, ref nothing);164 newdoc.Tables[1].Cell(1, 1).Range.Text = "产品\n项目";165 newdoc.Tables[1].Cell(1, 2).Range.Text = "电脑";166 newdoc.Tables[1].Cell(1, 3).Range.Text = "手机";167 newdoc.Tables[1].Cell(2, 1).Range.Text = "重量(kg)";168 newdoc.Tables[1].Cell(3, 1).Range.Text = "价格(元)";169 newdoc.Tables[1].Cell(4, 1).Range.Text = "共同信息";170 newdoc.Tables[1].Cell(4, 2).Range.Text = "信息A";171 newdoc.Tables[1].Cell(4,3).Range.Text = "信息B";172 173 174 table1.Select();175 table1.Rows.Alignment = Word.WdRowAlignment.wdAlignRowCenter;//整个表格居中176 newapp.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;177 newapp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;178 newapp.Selection.Cells.HeightRule = Word.WdRowHeightRule.wdRowHeightExactly;179 newapp.Selection.Cells.Height = 40;180 table1.Rows[2].Height = 20;181 table1.Rows[3].Height = 20;182 table1.Rows[4].Height = 20;183 table1.Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;184 newapp.Selection.Cells.Width=150;185 table1.Columns[1].Width = 75;186 table1.Cell(1, 1).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;187 table1.Cell(1, 1).Range.Paragraphs[2].Format.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft;188 189 190 191 192 //表头斜线193 table1.Cell(1, 1).Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderDiagonalDown ].Visible = true;194 table1.Cell(1, 1).Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderDiagonalDown].Color = Word.WdColor.wdColorGreen;195 table1.Cell(1, 1).Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderDiagonalDown].LineWidth = Word.WdLineWidth.wdLineWidth050pt;196 197 //表格边框198 table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderHorizontal ].Visible = true;199 table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderHorizontal].Color = Word.WdColor.wdColorGreen;200 table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderHorizontal].LineWidth = Word.WdLineWidth.wdLineWidth050pt;201 202 table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderVertical].Visible = true;203 table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderVertical].Color = Word.WdColor.wdColorGreen;204 table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderVertical].LineWidth = Word.WdLineWidth.wdLineWidth050pt;205 206 table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderLeft].Visible = true;207 table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderLeft].Color = Word.WdColor.wdColorGreen;208 table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderLeft].LineWidth = Word.WdLineWidth.wdLineWidth050pt;209 table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderLeft].LineStyle = Word.WdLineStyle.wdLineStyleDoubleWavy;210 211 table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderRight].Visible = true;212 table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderRight].Color = Word.WdColor.wdColorGreen;213 table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderRight].LineWidth = Word.WdLineWidth.wdLineWidth050pt;214 table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderRight].LineStyle = Word.WdLineStyle.wdLineStyleDoubleWavy;215 216 table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom ].Visible = true;217 table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].Color = Word.WdColor.wdColorGreen;218 table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].LineWidth = Word.WdLineWidth.wdLineWidth050pt;219 table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderBottom].LineStyle = Word.WdLineStyle.wdLineStyleDouble;220 221 table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderTop ].Visible = true;222 table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderTop].Color = Word.WdColor.wdColorGreen;223 table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderTop].LineWidth = Word.WdLineWidth.wdLineWidth050pt;224 table1.Borders[Microsoft.Office.Interop.Word.WdBorderType.wdBorderTop].LineStyle = Word.WdLineStyle.wdLineStyleDouble;225 226 //合并单元格227 newdoc.Tables[1].Cell(4, 2).Merge(table1.Cell(4, 3));228 229 //删除图片230 this.delpictfile(headerfile);231 this.delpictfile(picname);232 233 234 //保存文档235 object name = "c:\\yb3.doc";236 newdoc.SaveAs(ref name, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing,237 ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing, ref nothing,238 ref nothing, ref nothing);239 240 //关闭文档241 object saveOption = Word.WdSaveOptions.wdDoNotSaveChanges;242 newdoc.Close(ref nothing , ref nothing, ref nothing);243 newapp.Application.Quit(ref saveOption, ref nothing, ref nothing);244 newdoc = null;245 newapp = null;246 ShellExecute(IntPtr.Zero, "open", "c:\\yb3.doc", "", "", 3);247 }248 249 private void outpicture(string filename,System.Drawing.Bitmap bmap)250 {251 bmap.Save(filename);252 }253 254 private void delpictfile(string filename)255 {256 System.IO.File.Delete(filename);257 }258 259 }260 261 }