操作Word
1. 安装Office,添加引用COM里面的 Microsoft Word 14.0 Object. Library 2. 导命名空间 using MsWord =Microsoft.Office.Interop.Word; 3. 创建Word应用程序 把引用中的Microsoft.Office.Interop.Word属性中的嵌入互操作设为False 创建Word应用程序 MsWord .Application wordApp = new MsWord.ApplicationClass(); 使其可见: wordApp.Visible = true; 4. 创建Word文档对象: MsWord.DocumentwordDoc = wordApp.Documents.Add();创建空文档 根据aaa这个模板来创建新的文档 MsWord.DocumentwordDoc = wordApp.Documents.Add(@"E:\aaa.doc"); 5. 打开Word文档 MsWord.DocumentwordDoc = wordApp.Documents.Open(@"E:\aaa.doc"); 6. 向word中添加内容 //加内容 MsWord.Application wordApp = new MsWord.ApplicationClass(); MsWord.Document wordDoc = wordApp.Documents.Add(); //Paragraphs是段落,可直接add,这里是最后一段范围 wordDoc.Paragraphs.Last.Range.Text = "这是第一行\n"; wordDoc.Paragraphs.Last.Range.Text = "第二行开始了";//不加\n会被覆盖 wordDoc.Paragraphs.Last.Range.Text = "会覆盖的"; //直接添加段,不是覆盖 wordDoc.Paragraphs.Last.Range.Text += "不会覆盖的"; //添加在此段的文字后面,不是新段落 wordDoc.Paragraphs.Last.Range.InsertAfter("这是后面的内容"); wordApp.Visible = true; 7. 保存 wordApp.Visible = false; //不可见直接保存 wordDoc.SaveAs2(@"E:\bbb.docx");//保存 wordDoc.Close(true);//关闭 wordApp.Quit();//释放Word进程 8. 操作字体 //字体 wordDoc.Paragraphs.Last.Range.Font.Bold = 1; wordDoc.Paragraphs.Last.Range.Font.Italic = 1; wordDoc.Paragraphs.Last.Range.Font.Size = 32; wordDoc.Paragraphs.Last.Range.Font.Name = "楷体"; wordDoc.Paragraphs.Last.Range.Font.Underline = MsWord.WdUnderline.wdUnderlineDash; wordDoc.Paragraphs.Last.Range.Font.ColorIndex = MsWord.WdColorIndex.wdPink; 9. 创建表格 //表格,5行5列 MsWord.Table table = wordDoc.Paragraphs.Last.Range.Tables.Add (wordDoc.Paragraphs.Last.Range,5,5); //设置边线可见 table.Borders.Enable = 1; table.Borders.InsideColor = MsWord.WdColor.wdColorBlue; table.Borders.OutsideColor = MsWord.WdColor.wdColorBlack; table.Borders.OutsideLineWidth = MsWord.WdLineWidth.wdLineWidth025pt; //表格加内容 for(inti =1 ;i<=5;i++) { for (int j = 1; j <= 5; j++) { table.Rows[i].Cells[j].Range.Text="第i行,第j列"; } //下面这行代码设置表格一行的背景色 table.Rows[i].Shading.BackgroundPatternColor = MSWord.WdColor.wdColorDarkYellow; 10.如何插入图片? wordDoc.InlineShapes.AddPicture(@"E:\cyl.jpg",false,true); //设置图片宽高的绝对大小 //wordDoc.InlineShapes[1].Width = 200; //wordDoc.InlineShapes[1].Height = 150; //按比例缩放大小 wordDoc.InlineShapes[1].ScaleWidth = 30; wordDoc.InlineShapes[1].ScaleHeight = 30; 11. 如何操作书签,在书签处添加内容 wordDoc.Bookmarks["xingming"].Range.Text = "马晨"; wordDoc.Bookmarks["xingbie"].Range.Text = "男"; wordDoc.Bookmarks["minzu"].Range.Text = "汉族"; wordDoc.Bookmarks["shengri"].Range.Text = "1991-6-1"; wordDoc.Bookmarks["zhengzhimianmao"].Range.Text = "共青团员"; wordDoc.Bookmarks["zhaopian"].Range.InlineShapes.AddPicture(@"e:\cyl.jpg"); wordDoc.Bookmarks["zhaopian"].Range.InlineShapes[1].Width = 80; wordDoc.Bookmarks["zhaopian"].Range.InlineShapes[1].Height = 100; 12. 打印预览及打印 打印预览: wordDoc.PrintPreview(); 打印 wordDoc.PrintOut(); 13. 注意:在隐藏的时候一定要注意代码最后写上关闭文档和程序 wordApp.Visible = false; wordDoc.Close(false); wordApp.Quit();