SpringBoot使用FreeMarker根据模板导出Word
前言
提示:以下是本篇文章正文内容,下面案例可供参考
一、简单模板准备
示例:新建word文档,后缀改为doc。freemarker目前只支持doc格式导出(最好使用office)
然后另存为Word2003XML文档格式(不是word XML)
复制xml代码,格式化
把格式化好的代码 复制到xml内
二、把xml文件后缀改成.ftl
将ftl文件放入项目
打开ftl文件
将值改成对应的key键
模板设置完成
Java代码如下(示例):
Service层:
/** * 导出Word * @param response * @throws Exception */ public void fileOutWord(HttpServletResponse response) throws Exception{ Map<String,Object> map = new HashMap<>(); map.put("name","刘老四"); map.put("sex","男"); WordUtils.template2Word("moban.ftl",map,"test",response); }
Controller层:
@RequestMapping(value = "/fileOutWord", method = { RequestMethod.POST,RequestMethod.GET}) public void fileOutWord(HttpServletResponse response){ try { elementTestService.fileOutWord(response); }catch (Exception e){ e.printStackTrace(); } }
工具类
public class WordUtils { public static void template2Word(String templateName, Map<String, Object> data, String fileName, HttpServletResponse response) throws Exception{ fileName = new String(fileName.getBytes("GBK"), StandardCharsets.ISO_8859_1) + ".doc"; response.setContentType("application/x-msdownload;charset=UTF-8"); response.addHeader("Content-Disposition", "attachment;filename=" + fileName + ";charset=UTF-8"); Configuration configuration = new Configuration(Configuration.getVersion()); configuration.setDefaultEncoding("UTF-8"); // 设置模板存放的路径 configuration.setClassForTemplateLoading(WordUtils.class, "/template"); Writer writer = new OutputStreamWriter(response.getOutputStream()); Template t = configuration.getTemplate(templateName); t.process(data, writer); }
测试导出结果
本章只是实例,样式可随意更改 key键对应即可