C#通过模板导出Word的两种方法(超简单)

您所在的位置:网站首页 office导入dot模板 C#通过模板导出Word的两种方法(超简单)

C#通过模板导出Word的两种方法(超简单)

2023-09-07 18:21| 来源: 网络整理| 查看: 265

方法一:使用Office的组件

==使用该方法必须要安装Office==

1、制作Word模板 Word模板

在需要填充内容的地方增加标识符号,方便之后替换使用,例如 ==[项目名称]==,其中[]符号和中间的文字可根据个人情况进行修改。

到此模板已经制作完成,是不是很简单。

2、操作Word 2.1 引用Microsoft.Office.Interop.Word.dll

添加命名空间

using Word = Microsoft.Office.Interop.Word; 2.2 编码开始 string mubanFile = "模板.docx"; string templatePath = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, mubanFile); Dictionary bookmarks = new Dictionary(); var item=xxx;//数据源 //将数据与Word模板中的标签对应 bookmarks.Add("[姓名]", item.UserName); bookmarks.Add("[性别]", item.Sex); bookmarks.Add("[出生年月]", item.BirthDay); bookmarks.Add("[民族]", item.Ethnic); bookmarks.Add("[文化程度]", item.EducationalLevel); bookmarks.Add("[详细地址]", item.Address); bookmarks.Add("[电话]", item.Phone); string wordpath = outputPath + "xx.docx";//导出word地址 string pdfpath = outputPath + "xx.pdf";//导出pdf地址 GenerateWord(templatePath, wordpath, pdfpath, bookmarks); /// /// 根据word模板文件导出word/pdf文件 /// /// 模板路径 /// 导出文件名称 /// pdf文件名称 /// 模板内书签集合 public static void GenerateWord(string templateFile, string fileNameWord, string fileNamePdf, Dictionary bookmarks) { Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application(); File.Copy(templateFile, fileNameWord, true); Microsoft.Office.Interop.Word.Document doc = new Microsoft.Office.Interop.Word.Document(); object Obj_FileName = fileNameWord; object Visible = false; object ReadOnly = false; object missing = System.Reflection.Missing.Value; object IsSave = true; object FileName = fileNamePdf; object FileFormat = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatPDF; object LockComments = false; object AddToRecentFiles = true; object ReadOnlyRecommended = false; object EmbedTrueTypeFonts = false; object SaveNativePictureFormat = true; object SaveFormsData = false; object SaveAsAOCELetter = false; object Encoding = Microsoft.Office.Core.MsoEncoding.msoEncodingSimplifiedChineseGB18030; object InsertLineBreaks = false; object AllowSubstitutions = false; object LineEnding = Microsoft.Office.Interop.Word.WdLineEndingType.wdCRLF; object AddBiDiMarks = false; try { 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(); foreach (string bookmarkName in bookmarks.Keys) { string newstr; string newStrs; replace(doc, bookmarkName, bookmarks[bookmarkName]);//替换内容 } //replace(doc, "hello", "shalv"); //此处存储时,参数可选填,如需另外生成pdf,加入一个参数ref FileName, doc.SaveAs(ref FileName, ref FileFormat, ref LockComments, ref missing, ref AddToRecentFiles, ref missing, ref ReadOnlyRecommended, ref EmbedTrueTypeFonts, ref SaveNativePictureFormat, ref SaveFormsData, ref SaveAsAOCELetter, ref Encoding, ref InsertLineBreaks, ref AllowSubstitutions, ref LineEnding, ref AddBiDiMarks); doc.Close(ref IsSave, ref missing, ref missing); } catch (Exception ex) { LogHelper.WriteLog(ex.ToString()); doc.Close(ref IsSave, ref missing, ref missing); } } /// /// 在word 中查找一个字符串直接替换所需要的文本 /// /// 原文本 /// 新文本 /// public static void replace(Microsoft.Office.Interop.Word.Document doc, string strOldText, string strNewText) { doc.Content.Find.Text = strOldText; object FindText, ReplaceWith, Replace;// object MissingValue = Type.Missing; FindText = strOldText;//要查找的文本 ReplaceWith = strNewText;//替换文本 Replace = Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll; /*wdReplaceAll - 替换找到的所有项。 * wdReplaceNone - 不替换找到的任何项。 * wdReplaceOne - 替换找到的第一项。 * */ doc.Content.Find.ClearFormatting();//移除Find的搜索文本和段落格式设置 doc.Content.Find.Execute( ref FindText, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref ReplaceWith, ref Replace, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue); }

好了,到这就完成了。

不过有个小问题,这种替换的方式,当要替换的字符串超过一定的长度,就会提示“字符串参量过长”,搜索发现,==替换的最大长度为255字符==。

下面是解决方法 在替换前判断替换内容长度是否超过255,如果超长就分段替换,代码如下

foreach (string bookmarkName in bookmarks.Keys) { int len = bookmarks[bookmarkName].Length; int cnt = len / 255; string newstr; string newStrs; if (bookmarks[bookmarkName].Length < 255) { replace(doc, bookmarkName, bookmarks[bookmarkName]);//替换内容 } else { for (int i = 0; i


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3