记录下使用C#+Word模板导出Word文件的方法。
首先建立Word文件模板,需要填写的地方用占位符替代,比如姓名处:name,年龄处:age....
首先引入命名空间:
using word = Microsoft.Office.Interop.Word
下面是代码实现:
word.Application app = new word.Application(); app.Visible = false; word.Document doc = app.Documents.Open(path);//参数为模板路径 doc.Activate(); object flag1 = true; object flag2 = false; Dictionary<object, object> list = new Dictionary<object, object>();//要替换的字符 list.Add("Name", "张三"); list.Add("Age", "29"); list.Add("Address", "北京市"); object wrap = word.WdFindWrap.wdFindContinue; object replace = word.WdReplace.wdReplaceAll; foreach (var v in list) { object findText = v.Key, replaceText = v.Value; app.Selection.Find.Execute(ref findText, ref flag1, ref flag2, ref flag2, ref flag2, ref flag2, ref flag1, ref wrap, ref flag1, ref replaceText, ref replace, ref flag2, ref flag2, ref flag2, ref flag2); } doc.SaveAs2(path2);//导出文件,指定文件路径及名称 doc.Close(); app.Quit();
标签:word,C#,app,list,flag2,Word,ref,模板 From: https://www.cnblogs.com/cfsl/p/17058548.html