如题,c#操作word,向word模版标签处添加文字内容:
public void word() { //模板文件 string templateFile = Path.GetFullPath("../FileWord/w1.docx").Replace("\bin", ""); //模板路径 //生成的具有模板样式的新文件 string fileName = Path.GetFullPath("../WordData/w3.docx").Replace("\bin", ""); //另存为的路径 ExportWord(templateFile, fileName); } /// <summary> /// 调用模板生成word /// </summary> /// <param name="templateFile">模板文件</param> /// <param name="fileName">生成的具有模板样式的新文件</param> public void ExportWord(string templateFile, string fileName) { //生成word程序对象 Word.Application app = new Word.Application(); Word.Document doc = new Word.Document(); try { //模板文件 string TemplateFile = templateFile; //生成的具有模板样式的新文件 string FileName = fileName; //模板文件拷贝到新文件 File.Copy(TemplateFile, FileName,true);//允许覆盖同名文件 //File.Copy(TemplateFile, FileName);//不允许覆盖同名文件 //生成documnet对象 object Obj_FileName = FileName; object Visible = false; object ReadOnly = false; object missing = System.Reflection.Missing.Value; //打开文件 doc = app.Documents.Open(ref Obj_FileName, ref missing, ref ReadOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref Visible, ref missing, ref missing, ref missing, ref missing); doc.Activate(); //按照标签名称定位标签位置(也可以循环标签进行操作) object WordMarkName = "医院名称";//word模板中的书签名称 object what = Word.WdGoToItem.wdGoToBookmark; doc.ActiveWindow.Selection.GoTo(ref what, ref missing, ref missing, ref WordMarkName);//光标转到书签的位置 doc.ActiveWindow.Selection.TypeText("XXXX");//插入的内容,插入位置是word模板中书签定位的位置 //doc.ActiveWindow.Selection.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;//设置当前定位书签位置插入内容的格式 //doc.ActiveWindow.Selection.TypeParagraph();//回车换行 //输出完毕后关闭doc对象 object IsSave = true; doc.Close(ref IsSave, ref missing, ref missing); app.Quit(); MyHelper.Show("生成“" + FileName + "”成功!", "提示"); } catch (Exception Ex) { //关闭doc对象 object IsSave = true; object missing = System.Reflection.Missing.Value; doc.Close(ref IsSave, ref missing, ref missing); app.Quit(); MyHelper.Show(Ex.ToString(), "提示"); return; } }
附循环标签操作代码:
foreach (Word.Bookmark bk in doc.Bookmarks) { if (bk.Name == "name") { bk.Range.Text = "Hyman";//插入文字 } else if (bk.Name == "picture") { bk.Select(); Word.Selection sel = app.Selection; sel.InlineShapes.AddPicture("D:\Test.jpg");//插入图片 } }