先把word模板整好,显示数据的地方用 ${参数} 取值,然后保存成.xml格式,不要直接改后缀,然后放到你的项目下的resources 目录下 修改后缀名为 .ftl
前端无返回值请求,如果是有list要在你的模板循环展示的位置添加<#list list as item> 别忘了在结尾位置加上结束标签</#list>
@Resource
private FreeMarkerConfigurer freeMarkerConfigurer;
@RequestMapping("/download")
public void download(HttpServletRequest request , HttpServletResponse response){
OutputStreamWriter outputStreamWriter = null;
try {
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("reimbursementName", reimbursement.getName());
paramMap.put("number", "");
Company company = companyService.findById(Integer.valueOf(reimbursement.getCompany()));
if(company != null){
paramMap.put("company", company.getName());
}else {
paramMap.put("company","");
}
paramMap.put("sumMoneyYuan",MoneyUtil.change(sumMoneyAll));
paramMap.put("sumMoney",sumMoneyAll);
paramMap.put("reimbursementExplains", reimbursement.getExplains());
paramMap.put("user", reimbursement.getUser());
paramMap.put("list", list);
// 告诉浏览器用什么软件可以打开此文件
response.setContentType("application/octet-stream");
// 下载文件的默认名称
String datetime = DateTimeUtil.getNewDateSimpleDateFormat("yyyyMMddHHmmss");
String name = URLEncoder.encode("出差费用报销单"+datetime, "UTF-8") + ".doc";
response.setHeader("Content-Disposition", "attachment;filename=" + name);
freeMarkerConfigurer.getConfiguration().setClassForTemplateLoading(getClass(), "/templates");
Template template = freeMarkerConfigurer.getConfiguration().getTemplate("reimbursement.ftl");
outputStreamWriter = new OutputStreamWriter(response.getOutputStream(), "utf-8");
template.process(paramMap, outputStreamWriter);
outputStreamWriter.close();
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
}