首先创建word文档,编辑好模板,使用 ${} 作为媒介标识待填入的值
另存为xml格式
改为ftl格式
上传至项目目录下
/**
* 1, 新建一个word文档, 输入模板内容:值用${}代替 比如-> 姓名:${name}
* 2, 将该word文件另存为xml格式(注意是另存为,不是直接改扩展名)
* 3, 将xml文件的扩展名直接改为ftl模板
* 4, 用java代码完成导出(需要导入freemarker.jar)
* 指定ftl文件所在目录路径的方式,注意是
* 指定ftl文件所在目录的路径,而不是ftl文件的路径
* @param TemplatePath ftl模板路径
* @param dataMap 模板替换值
*/
@ApiOperation(value="测试获取word")
@PostMapping(value = "/WordDownload")
public Result<?> WordDownload() {
//封装需要替换的值,替换模板${}里面的值
Map<String,Object> dataMap = new HashMap<>();
dataMap.put("title", "qwer");
dataMap.put("id", "123658749");
dataMap.put("name", "张三");
dataMap.put("content", "张三qwer001");
dataMap.put("time", new SimpleDateFormat("yyyy年MM月dd日").format(new Date()));
boolean b = WordUtil.uploadWord(TemplatePath,dataMap,response);
if (b){
return Result.ok("操作成功");
}
return Result.error("操作失败");
}
public static boolean uploadWord(String TemplatePath,Map<String,Object> dataMap,HttpServletResponse response){
try {
//Configuration 用于读取ftl文件
Configuration configuration = new Configuration(new Version("2.3.0"));
configuration.setDefaultEncoding("utf-8");
//指定模板文件路径
//指定路径
configuration.setDirectoryForTemplateLoading(new File(TemplatePath));
//configuration.setDirectoryForTemplateLoading(new File("jeecg-boot-module-system"+File.separator+"src"+File.separator+"main"+File.separator+"resources"+File.separator+"test"));
//以utf-8的编码读取ftl文件
response.setContentType("application/msword;charset=utf-8");
response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("test"+ System.currentTimeMillis()+".doc","UTF-8"));
//此句非常关键,不然word文档全是乱码
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
//以utf-8的编码读取ftl文件
Template template = configuration.getTemplate("test.ftl","utf-8");
template.process(dataMap, out);
out.close();
return true;
} catch (Exception e) {
log.error("导出失败"+e.getMessage());
return false;
}
}
使用postman 调用下载测试 结果