java通过FreeMarker模板生成Excel文件之.ftl模板制作

时间:2022-07-02 20:55:59

关于怎么通过freemarker模板生成excel的文章很多,关键点在于怎么制作模板文件.ftl

网上的办法是:

(1)把Excel模板的格式调好,另存为xml文件
(2)新建一个.ftl文件,把xml文件内容copy进去,把变量换成FreeMarker的插值
  当然可行,但是这样制作的.ftl文件偏大,可读性很低
  
 我是这样制作的,直接写HTML标签
<table>
<thead>
<tr>
<td>资产端简称</td>
<td>放款金额(元)</td>
<td>账单月份</td>
<td>UZY服务费(元)</td>
<td>账单状态</td>
</tr>
</thead> <tbody>
<#list dataList as data>
<tr>
<td>${(data.assetName)!""}</td>
<td>${(data.loanAmount?string('0.00'))!""}</td>
<td>${(data.billMonth)!""}</td>
<td>${(data.uzyServiceFee?string('0.00'))!""}</td>
<td>${(data.statusName)!""}</td>
</tr>
</#list>
</tbody>
</table>
简单吧,效果如下

java通过FreeMarker模板生成Excel文件之.ftl模板制作

后台部分代码:

private void exportToXls(String templateName, String fileName, Map<String, Object> dataMap, HttpServletResponse response) {
Configuration configuration = new Configuration();
configuration.setEncoding(Locale.CHINA, "UTF-8");
configuration.setDefaultEncoding("UTF-8");
configuration.setClassForTemplateLoading(this.getClass(), "/templates");
String downloadFileName;
try {
downloadFileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
} catch (UnsupportedEncodingException e) {
logger.warn("encode error", e);
downloadFileName = DateUtil.format(new Date());
}
response.setContentType("application/ms-excel");
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-disposition", "attachment; filename=" + downloadFileName + ".xls");
try {
Template template = configuration.getTemplate(templateName);
template.process(dataMap, response.getWriter());
} catch (Exception e) {
logger.warn("export report error", e);
}
}