1. 新建一个test.docx文件,添加表格,并用${}声明一些参数
2. test.docx文件另存为xml文件,不要直接改docx后缀,然后修改xml后缀为ftl文件。
3.springboot项目添加freemarker相关包,我直接引入的
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency>4. 我这边是把第二步的test.ftl文件放到了项目里面
5 .
@GetMapping("/test") @ResponseBody public void test(HttpServletRequest request,HttpServletResponse response){ try { Map<String,Object> dataMap = new HashMap<String, Object>(); //编号 dataMap.put("id", "123456"); //日期 dataMap.put("date", new SimpleDateFormat("yyyy年MM月dd日").format(new SimpleDateFormat("yyyy-MM-dd").parse("2018-09-19"))); //附件张数 dataMap.put("number", 1); //受款人 dataMap.put("name", "张三"); Configuration configuration = new Configuration(new Version("2.3.0")); configuration.setDefaultEncoding("utf-8"); /** * configuration读取ftl文件有三种方式,区别可以百度,Configuration和Version均是引入的freemarker.template包下的 * 指定ftl文件所在目录的路径,而不是ftl文件的路径 */ //读取配置文件地址 String path = ResourceUtils.getURL("classpath:resources/ftl").getPath(); configuration.setDirectoryForTemplateLoading(new File(path)); /** * 下载到本地 */ // File outFile = new File("D:/报销信息导出.doc"); // //以utf-8的编码读取ftl文件 // Template template = configuration.getTemplate("test.ftl", "utf-8"); // Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"), 10240); // template.process(dataMap, out); // out.close(); /** * 浏览器直接下面显示下载 */ response.setContentType("application/msword"); //filename我随便写的,可以用时间戳 response.setHeader("Content-Disposition", "attachment;filename=\"" + new String((111+"侦查要报.doc").getBytes("GBK"), "iso8859-1") + "\""); response.setCharacterEncoding("utf-8");// 此句非常关键,不然word文档全是乱码 PrintWriter out = response.getWriter(); Template t = configuration.getTemplate("test.ftl", "utf-8");// 以utf-8的编码读取ftl文件 t.process(dataMap, out); out.close(); } catch (Exception e) { e.printStackTrace(); }}