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


  關於怎么通過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>
簡單吧,效果如下

 

后台部分代碼:

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);
}
}

 



 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM