首页 > 编程知识 正文

c# winform word模板 利用WORD 书签 定位替换 生成 WORD

时间:2023-05-03 14:05:21 阅读:274627 作者:1235

private void button1_Click(object sender, EventArgs e) { //模板文件 string templateFile = @"Word模板.doc"; //生成的具有模板样式的新文件 string fileName = @"F:WinMainbinDebug" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".doc"; ExportWord(templateFile, fileName); } #region MyRegion /// <summary> /// 调用模板生成word /// </summary> /// <param name="templateFile">模板文件</param> /// <param name="fileName">生成的具有模板样式的新文件</param> public void ExportWord(string templateFile, string fileName) { try { //生成word程序对象 Word.Application app = new Word.Application(); //模板文件 string TemplateFile = templateFile; //生成的具有模板样式的新文件 string FileName = fileName; //模板文件拷贝到新文件 File.Copy(TemplateFile, FileName); //生成documnet对象 Word.Document doc = new Word.Document(); 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(); int WordNum = 4;//书签个数 //将光标转到模板中定义的书签的位置,插入所需要添加的内容,循环次数与书签个数相符 for (int WordIndex = 1; WordIndex <= WordNum; WordIndex++) { object WordMarkName = "书签名称" + WordIndex.ToString();//word模板中的书签名称 object what = Word.WdGoToItem.wdGoToBookmark; doc.ActiveWindow.Selection.GoTo(ref what, ref missing, ref missing, ref WordMarkName);//光标转到书签的位置 doc.ActiveWindow.Selection.TypeText("插入的内容" + WordIndex.ToString());//插入的内容,插入位置是word模板中书签定位的位置 doc.ActiveWindow.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;//设置当前定位书签位置插入内容的格式 //doc.ActiveWindow.Selection.TypeParagraph();//回车换行 } //输出完毕后关闭doc对象 object IsSave = true; doc.Close(ref IsSave, ref missing, ref missing); app.Quit(ref missing, ref missing, ref missing); MessageBox.Show("生成“" + FileName + "”成功!"); } catch (Exception Ex) { MessageBox.Show(Ex.ToString()); return; } } #endregion

//需要引入的DLL
using System.IO;
using Microsoft.Office.Core;//COM选项卡中的"Microsoft Office 11.0 Object Library"
using Word = Microsoft.Office.Interop.Word;//.NET选项卡中的"Microsoft.Office.Interop.Word"

WORD 模板:

待插入内容标题1

 

待插入内容标题2

 

待插入内容标题3

 

待插入内容标题4

 

word 书签插入方法:

设置书签方法/步骤

 

将光标定位到要设置书签的地方,或选中要设置书签的文字,点击“插入”菜单 下的“书签”。

2

输入书签名,点击“添加”即可。注意,书签名必须以字母或汉字开头,可以包含数字和下划线,但不能包含“@”、“#”、“~”等符号。

END

使用书签方法/步骤2

点击“插入”菜单下的“书签”,双击已有的书签可以直接跳转到书签处,或选中书签,点击“定位”,也可以跳转到书签处。

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。