前提:电脑上需要安装Office
第一步:添加引用。Microsoft.Word.xxx.Object.Library
注意:把引用中的Microsoft.Office.Interop.Word的属性中的“嵌入互操作”设为false。否则上面的代码会报错。
第二步:导入命名空间。using MSWord = Microsoft.Office.Interop.Word;//MCWord可以用来替代Microsoft.Office.Interop.Word
第三步:创建Word应用程序。
MSWord.Application wordApp = new MSWord.ApplicationClass();
第四步:操作Word
1、新建
MSWord.Document wordDoc = wordApp.Documents.Add();//创建一个空文档 MSWord.Document wordDoc = wordApp.Documents.Add(@"E:\aaa.docx");//根据指定的word文档创建新的文档 //使其可见 wordApp.Visible = true;
2、打开
MSWord.Document wordDoc = wordApp.Documents.Open(@"E:\aaa.docx");//打开指定路径下的word文档
3、向word中添加内容
wordDoc.Paragraphs.Last.Range.Text = "这是第一行\n"; //将覆盖最后一个段落的内容 wordDoc.Paragraphs.Last.Range.InsertAfter("这是后面的内容"); //在最后一个段落的末尾追加内容 wordDoc.Paragraphs.Last.Range.InsertBefore("这是后面的内容"); //在最后一个段落的开始插入内容
4、保存文档
wordDoc.SaveAs2(@"E:\bbb.docx");
5、关闭Word文档
wordDoc.Close(true);
6、退出Word应用程序
wordApp.Quit();
7、操作字体
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.wdUnderlineDotDotDash; wordDoc.Paragraphs.Last.Range.Font.ColorIndex = MSWord.WdColorIndex.wdRed; wordDoc.Paragraphs.Last.Range.Text = "这是修改后的字体样式";
8、操作单元格
MSWord.Document wordDoc = wordApp.Documents.Add(); //造一个5行5列的table表格 MSWord.Table table = wordDoc.Paragraphs.Last.Range.Tables.Add(wordDoc.Paragraphs.Last.Range,5,5); table.Borders.Enable = 1; //设置边框可见 table.Borders.InsideColor = MSWord.WdColor.wdColorRed; table.Borders.OutsideColor = MSWord.WdColor.wdColorBlue; table.Borders.OutsideLineWidth = MSWord.WdLineWidth.wdLineWidth225pt; //给表格中的单元格添加内容 for (int i = 1; i <= 5; i++) { if (i == 1) { table.Rows[i].Shading.BackgroundPatternColor = MSWord.WdColor.wdColorDarkYellow; } for (int j = 1; j <= 5; j++) { table.Rows[i].Cells[j].Range.Text = "第" + i + "行,第" + j + "列"; } } wordApp.Visible = true; //下面这行代码设置表格一行的背景色 table.Rows[i].Shading.BackgroundPatternColor = MSWord.WdColor.wdColorDarkYellow;
9、插入图片
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;
10、操作书签
需要提前在Word文档中设置好书签
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;