Java动态插入数据到html模板并导出html解决方案
需求
前端页面数据点击下载为一个html,还必须可以打开关闭表格,有颜色样式之类可复制的,所以canvas画成一个pdf导出显然是不行了;
目前解决方案是:
前端: 给出html基础样式模板
后端: 使用FreeMarker模板引擎技术+打包下载+多选zip下载
FreeMarker模板引擎
FreeMarker简介:
- 主要内容
- FreeMarker概念
FreeMarker 是一款 模板引擎: 即一种基于模板和要改变的数据, 并用来生成输出文本(HTML网页,电子邮件,配置文件,源代码等)的通用工具。 是一个Java类库。
FreeMarker应用
maven导入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
编写工具类
@Slf4j
public class FreemarkerUtils {
@Data
public static class ReportFileVo{
private String fileName;
private String htmlString;
public ReportFileVo(){}
public ReportFileVo(String fileName,String htmlString){
this.fileName=fileName;
this.htmlString=htmlString;
}
}
/**
* 获取模板填充数据 返回填充数据后的html字符串
* @param templatePath 模板名称 (默认从/templates下找)
* @param map 模板填充数据
* @return
*/
public static String getTemplate(String templatePath, Map<String,Object> map) {
try {
Configuration cfg = new Configuration(Configuration.VERSION_2_3_30);
cfg.setClassForTemplateLoading(FreemarkerUtils.class, "/templates");
cfg.setDefaultEncoding("UTF-8");
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
cfg.setLogTemplateExceptions(true);
Template temp = cfg.getTemplate(templatePath);
StringWriter stringWriter = new StringWriter();
temp.process(map, stringWriter);
return stringWriter.toString();
}catch (Exception e) {
log.error("getTemplateFail", e);
}
return "";
}
/**
* html字符串解析成html文件前端下载
* @param vo html
* @param response
* @return
*/
public static Boolean htmlString2fileDownLoad(ReportFileVo vo, HttpServletResponse response) {
if(StringUtils.isEmpty(vo.getHtmlString())){
throw new ServiceException(500,"[html内容为空]");
}
String fileName = vo.getFileName();// 文件名
try {
fileName=new String(fileName.getBytes("UTF-8"),"ISO-8859-1");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
response.setContentType("application/force-download");// 设置强制下载不打开
response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
OutputStream os=null;
try {
byte[] bytes = vo.getHtmlString().getBytes(StandardCharsets.UTF_8);
os= response.getOutputStream();
os.write(bytes);
os.close();
} catch (Exception e) {
e.printStackTrace();
throw new ServiceException(500,"[下载失败]");
} finally {
if (null != os) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return true;
}
/**
* 多个html字符串打包成zip下载
*/
public static void zipFileDownload(Map<String, byte[]> byteList,HttpServletResponse response) {
try {
String fileName = System.currentTimeMillis()+".zip";// .zip名
response.setContentType("application/force-download");// 设置强制下载不打开
response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
OutputStream outputStream = response.getOutputStream();
ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
byteList.forEach((k, v) -> {
//写入一个条目,我们需要给这个条目起个名字,相当于起一个文件名称
try {
zipOutputStream.putNextEntry(new ZipEntry(k));
zipOutputStream.write(v);
} catch (IOException e) {
e.printStackTrace();
log.error("写入文件失败");
}
});
//关闭条目
zipOutputStream.closeEntry();
zipOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
log.error("压缩文件失败");
}
}
}
freemarker导入坐标后开箱即用,无需配置,工具类我这边把全部代码都贴出来了,在你的业务逻辑中处理完数据就可以直接调用
freemarker模板如何编写?我大概展示最简单的几种格式。详细语法在博客中搜的到有很多文章,自行寻找。
//直接插值 !代表为空就用后面那个空字符串
<span class="value">${name!' '}</span>
//对象属性直接插值
<span class="value">${executionRunLog.ruleName!' '}</span>
// if else判断 ??判断不为空
<#if executionRunLog.executionStatus?? && executionRunLog.executionStatus='SUCCESS'>
<b style="margin-left:0" class="default SUCCESS">COMPLETE</b>
<#else>
<b style="margin-left:0" class="default ${executionRunLog.executionStatus!' '}">${executionRunLog.executionStatus!' '}</b>
</#if>
//list for循环 这是list<String>, 如何里面是对象就用.对象属性取值
<#if executionRunLog.linkRequirement?? && (executionRunLog.linkRequirement?size > 0)>
<#list executionRunLog.linkRequirement as requirementId>
<button>
<a href="`https://jira.pg.com.cn/browse/${requirementId!' '}`" target="_blank" rel="noopener noreferrer">${requirementId!' '}</a>
</button>
</#list>
</#if>
//map取值
<#if logRecord['SUCCESS']?? >
<b class="default SUCCESS">Passed ${logRecord['SUCCESS']}</b>
</#if>
//map 循环
<#if setLog.executiveStatistics?? && (setLog.executiveStatistics?size > 0)>
<#list setLog.executiveStatistics?keys as key>
${key}:${setLog.executiveStatistics[key]};
</#list>
</#if>
END
码字不易,如果对你有帮助,请给个三连吧!