首页 > 代码库 > 操作Word
操作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();
操作Word
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。