一、maven添加freemarker模板引擎
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency>二、application.yml配置freemarker
# 设置freemarker freemarker: allow-request-override: false # 开发过程建议关闭缓存 cache: true check-template-location: false charset: UTF-8 content-type: text/html; charset=utf-8 expose-request-attributes: false expose-session-attributes: false expose-spring-macro-helpers: false request-context-attribute: # 默认后缀就是.ftl suffix: .ftl template-loader-path: classPath:/templates/code/一.word文档
1.单插表格
list表格 3.checkbox二、另存为xml文件
三、修改文件后缀为 .ftl 并添加到IDEA中,点击Code -> Reformat Code格式化代码。
1.变量有可能会分离,要手动调整,不知道怎么调整的可手动查看ftl文件中其他正确的地方是怎么写的。
变量分离情况 调整后2、单插表格变量 3.循环list表格,在下图 2 的位置加入循环语句,并把${id}改成 ${user.id} 4.checkbox,在后端添加一个控制checkbox的key-value,key为check,value为true/false 四、Controller代码(一份代码可执行以上3种格式)
@PostMapping("user/doc") @ResponseBody @ApiOperation(value="导出用户doc", httpMethod = "POST",produces="application/json",notes = "导出用户doc") public String exportDoc(String data) throws IOException{ Configuration configuration = new Configuration(); configuration.setDefaultEncoding("utf-8"); configuration.setClassForTemplateLoading(this.getClass(), "/templates/code"); Template template = configuration.getTemplate("test.ftl"); //data为Json格式 Map<String, String> dataMap = (Map<String, String>)JSON.parse(data); File outFile = new File("test.doc"); Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"UTF-8")); try { template.process(dataMap,out); out.flush(); out.close(); } catch (TemplateException e) { e.printStackTrace(); } return "导出成功"; }