一、创建ftl模板文件
1、将xls文件转换为xml格式
需要将xml中内容格式化一下, 在线 XML 格式化 | 菜鸟工具 (jyshare.com)
将格式化好的内容,保存在 ftl 文件中,放入项目文件。
二、后端对数据做组装
Java代码中对导出文件做赋值
@Overridepublic void exportFile(String cityId, Date filingTime, HttpServletRequest request, HttpServletResponse response) {try {String fileName = "xxxxx.xls";String tplType = "ftl/constructionSafetySupervision.ftl";response.reset();response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");response.setCharacterEncoding("utf-8");response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF8"));ConstructionSafetySupervision surveyDesignSupervision = new ConstructionSafetySupervision();surveyDesignSupervision.setFilingTime(filingTime);surveyDesignSupervision.setCityId(cityId);List<ConstructionSafetySupervision> list = this.mapper.findList2(surveyDesignSupervision);TemplateResourceUtils.renderResponse(response.getWriter(), new TemplateResourceUtils.AbstractTemplateMap() {@Overrideprotected void getMapData(Map<String, Object> map) {map.put("empList", list);map.putAll(TemplateResourceUtils.getYearMouth(surveyDesignSupervision.getFilingTime()));}}, tplType, UserUtils.getUser().getId());FileUtil.deleteAllFilesOfDir(new File(System.getProperty("user.dir") + File.separator + "static/" + UserUtils.getUser().getId()));} catch (Exception e) {e.printStackTrace();}}
String tplType = "ftl/constructionSafetySupervision.ftl"; 模板所属路径
设置返回体的类型
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
存放文件名称 filename,URLEncoder.encode工具类将带有汉字的文件名做转换
response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF8"));
这里的map存放的就是在模板中需要遍历的数据集
@Overrideprotected void getMapData(Map<String, Object> map) {map.put("empList", list);map.putAll(TemplateResourceUtils.getYearMouth(surveyDesignSupervision.getFilingTime()));
将数据传入到流中写入到文件里
public static void renderResponse(Writer writer, AbstractTemplateMap templateMap, String templateFilePath ,String userId) throws Exception {Map<String,Object> map = Maps.newHashMap();templateMap.getMapData(map);String targetFilePath = System.getProperty("user.dir") + File.separator + "static/" + userId +File.separator + FileUtil.getFileName(templateFilePath);String content = FileUtils.getContentsAsString(getFile(templateFilePath,targetFilePath));FreeMarkers.renderResponse(writer ,content ,map);}
三、数据在 ftl 模板中如何遍历
<#list empList! as emp>
${emp.panelist!}
</#list>
list 中存放map的key ,${emp.panelist!} 由key.参数名组成
${emp.demonstrationTime?string('yyyy-MM-dd')} 时间需要格式转化一下