由于Aspose.Words 是收费的,我使用的是网上下载的破解版本
开发环境 VS2017,.Net Core 2.1项目
将下载的破解版的Aspose.Words.dll放入项目中的某个文件夹,项目直接添加引用
文件中添加引用 using Aspose.Words;
Word模板中,使用{$}标签替换,需要插入表格的地方,插入一个标签;以便在标签中插入需要的内容
代码示例
/// <summary>
/// DOC 模板替换
/// </summary>
/// <param name="enterpriseView">企业信息</param>
/// <param name="fileDirPath">Doc模板路径</param>
/// <param name="fileRelativePath">生成的新的Doc路径</param>
/// <returns></returns>
public static bool CreateProjectReport(EnterpriseView enterpriseView, string fileDirPath, out string fileRelativePath)
{
try
{
//获取word文档模板
string templetePath = fileDirPath;
if (File.Exists(templetePath))
{
string newTempletePath ="D:\\UploadFiles\\PdfFiles\\";
string newTempleteFileName = Guid.NewGuid().ToString() + ".doc";
if (!Directory.Exists(newTempletePath))
{
Directory.CreateDirectory(newTempletePath);
}
string newTempleteFullPath = newTempletePath + newTempleteFileName;
File.Copy(templetePath, newTempleteFullPath);
//读取word模板
ReplaceKey(enterpriseView, builder, doc);
//插入html数据项目附件信息,书签插入方式
Bookmark bk = doc.Range.Bookmarks["ProjectAttachFile"];
if (bk != null)
{
if (builder.MoveToBookmark("ProjectAttachFile"))
{
string html = "<table cellspacing=\"0\" cellpadding=\"0\" style=\"width: 452.05pt; border: 0.75pt solid #000000; border-collapse:collapse\"><tbody>";
html += "<tr style='height:24.7pt'>";
html += "<td style=\"width: 34.5pt; border-style:solid; border-width:0.75pt; padding-right:5.03pt; padding-left:5.03pt; vertical-align:middle\">";
html += "<p style=\"margin-top:0pt; margin-bottom:10pt;text-align:center;line-height:115 %; font-size:11pt\">";
html += "<span style = \"font-family:宋体\">序号</span></p> ";
html += "</td>";
html += "<td style=\"width:395.2pt; border-style:solid; border-width:0.75pt; padding-right:5.03pt; padding-left:5.03pt; vertical-align:middle\">";
html += "<p style=\"margin-top:0pt; margin-bottom:10pt;text-align:center;line-height:115 %; font-size:11pt\">";
html += "<span style = \"font-family:宋体\">附件名称</span></p> ";
html += "</td>";
html += "</tr>";
html += "</tbody></table>";
builder.InsertHtml(html);
bk.Remove();
}
}
doc.Save(newTempleteFullPath);
fileRelativePath=newTempleteFullPath;
}
else
{
fileRelativePath = "";
return false;
}
}
catch(Exception ex)
{
fileRelativePath = "";
return false;
}
}
/// <summary>
/// 模板替换字
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="entity"></param>
/// <param name="builder"></param>
public static void ReplaceKey<T>(T entity, DocumentBuilder builder, Aspose.Words.Document doc)
{
Type entityType = typeof(T);
PropertyInfo[] properties = entityType.GetProperties();
string entityName = entityType.Name;//实体类名称
if (entityName == "EnterpriseView")//企业信息
{
foreach (var p in properties)
{
string propteryName = "{$" + p.Name + "}";//需要替换的文本
object value = p.GetValue(entity);
if (value == null)
{
value = "";
}
doc.Range.Replace(propteryName, value.ToString(), new Aspose.Words.Replacing.FindReplaceOptions { });
}
}
}