引入jar包
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency>
ftl工具类
package com.example.demo; import freemarker.template.Configuration; import freemarker.template.Template; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.Map; public class FtlUtils { /** * 生成 word 文件 * * @param dataMap 待填充数据 * @param templateName 模板文件名称 * @param filePath 模板文件路径 * @param fileName 生成的 word 文件名称 * @param response 响应流 */ public static void createWord(Map dataMap, String templateName, String filePath, String fileName, HttpServletResponse response){ // 创建配置实例 Configuration configuration = new Configuration(Configuration.VERSION_2_3_28); // 设置编码 configuration.setDefaultEncoding(StandardCharsets.UTF_8.name()); // ftl模板文件 configuration.setClassForTemplateLoading(FtlUtils.class, filePath); try { // 获取模板 Template template = configuration.getTemplate(templateName); response.setHeader("Content-disposition","attachment;filename=" + URLEncoder.encode(fileName + ".doc", StandardCharsets.UTF_8.name())); // 定义输出类型 response.setContentType("application/msword"); Writer out = new BufferedWriter(new OutputStreamWriter(response.getOutputStream(),"UTF-8")); // 生成文件 template.process(dataMap, out); out.flush(); out.close(); } catch (Exception e){ e.printStackTrace(); } } }
通过ftl模板生成并下载word文档
//下载word文档 @RequestMapping(value = "/ftlWord") public void createFtl(HttpServletResponse response,String ftlname) { Map map = new HashMap(); map.put("name", "张三"); map.put("age", 20); map.put("sex","男"); FtlUtils.createWord(map, "test.ftl", "/ftl/", "测试文件", response); }
通过ftl预览word文档
//预览word文档 @RequestMapping(value = "/selectFtl") public String selectFtl(HttpServletResponse response) { Map map = new HashMap(); map.put("name", "张三"); map.put("age", 20); map.put("sex","男"); return "/ftl/test"; }