通过freemarker模板生成对应word 文档

参考资料

  1. 在线开发手册
  2. 导出word
  3. 资料
  4. Springboot+FreeMarker文件的上传和下载

具体的代码参考

一、Maven中pom文件引入

<!-- https://mvnrepository.com/artifact/org.freemarker/freemarker -->
<!-- word 模板引擎 -->
<dependency>
   <groupId>org.freemarker</groupId>
   <artifactId>freemarker</artifactId>
   <version>2.3.30</version>
</dependency>

二、编写代码前的步骤

  1. 首先创建好对应的word模板
  2. 根据word模板,把模板另存为XML 文件
  3. windows 记事本打开对应的文件,另存为 ftl 格式的文件
  4. 最后把 ftl 后缀的文件添加到项目中

三、通过Main方法调用生成对应的word文档

 public static void main(String[] args) throws IOException, TemplateException {
        // 1.创建配置
        Configuration configuration = new Configuration(Configuration.VERSION_2_3_30);
        // 2.加载模板
        String filePath = "D:\\code\\project\\projcet-controller\\src\\main\\resources" +
                "\\wordtemplete";
        configuration.setDirectoryForTemplateLoading(new File(filePath));

        // 3.设置编码格式
        String encoding = "UTF-8";
        configuration.setDefaultEncoding(encoding);
        // 4.设置模板异常类型
        configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);

        // 5.创建数据类型
        Map<String, Object> root = new HashMap<>();
        root.put("name", "张三");
        root.put("sex", "男");
        root.put("age", "18");
        root.put("sechool", "家里蹲");
        root.put("major", "家庭宅男");
        root.put("company", "家");

        // 6.获取模板
        Template temp = configuration.getTemplate("test.ftl");

        // 7.输出 重新生成word 文档
        Writer out = null;
        try {
            File outFile = new File("D:/test.doc");
            if (outFile.exists()){
                outFile.delete();
            }
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"UTF-8"));
            temp.process(root, out);
        } finally {
            out.close();
        }

四、通过浏览器的访问,生成对应的word文档

  1. controller层代码
 @GetMapping("/download")
    public String getwordFile(@Param("name") String name, @Param("wordTemplateName") String wordTemplateName,
                              HttpServletResponse response) {
      // 获取模板所在的项目文件路径
      String path =  ClassUtils.getDefaultClassLoader().getResource("wordtemplate").getPath();
        String templateName = "test.ftl";
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("name", name);
        resultMap.put("sex", "男");
        resultMap.put("age", "18");
        resultMap.put("sechool", "家里蹲");
        resultMap.put("major", "家庭宅男");
        resultMap.put("company", "家");
        try {
            CreatWordUtils.creadWordFileInBrower(response, path, templateName, resultMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "下载成功";
}
  1. common层代码
    public static void creadWordFileInBrower(HttpServletResponse response, String filePath, String tempalteName,
                                             Map<String, Object> resultMap) throws Exception {
        Template temp = getTemplate(filePath, tempalteName);
        File file = null;
        InputStream fin = null;
        ServletOutputStream out = null;
        try {
            // 调用工具类的createDoc方法生成Word文档  
            file = createFile(temp, resultMap);
            fin = new FileInputStream(file);
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/msword");
            // 设置浏览器以下载的方式处理该文件名  
            String fileName = "TEST_" + String.valueOf(System.currentTimeMillis()) + ".doc";
            response.setHeader("Content-Disposition", "attachment;filename=".concat(String.valueOf(URLEncoder.encode(fileName, "UTF-8"))));
            out = response.getOutputStream();
            // 缓冲区
            byte[] buffer = new byte[512];
            int bytesToRead = -1;
            // 通过循环将读入的Word文件的内容输出到浏览器中  
            while ((bytesToRead = fin.read(buffer)) != -1) {
                out.write(buffer, 0, bytesToRead);
            }
        } finally {
            if (fin != null) {
                fin.close();
            }
            if (out != null) {
                out.close();
            }
            if (file != null) {
                file.delete();
            }// 删除临时文件
        }
    }

    private static Template getTemplate(String filePath, String tempalteName) throws IOException {
        // 1.创建配置
        Configuration configuration = new Configuration(Configuration.VERSION_2_3_30);
        // 2.加载模板
        configuration.setDirectoryForTemplateLoading(new File(filePath));

        // 3.设置编码格式
        String encoding = "UTF-8";
        configuration.setDefaultEncoding(encoding);
        // 4.设置模板异常类型
        configuration.setTemplateExceptionHandler(TemplateExceptionHandler.DEBUG_HANDLER);

        // 6.获取模板
        Template temp = configuration.getTemplate(tempalteName);

        return temp;
    }

    private static File createFile(Template temp, Map<String, Object> map) {
        String saveAllPath = "temp" + String.valueOf(System.currentTimeMillis()) + ".doc";
        // 7.输出 重新生成word 文档
        Writer out = null;
        File outFile = new File(saveAllPath);
        try {
            if (outFile.exists()) {
                outFile.delete();
            }
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8"));
            // 根据数据输出
            temp.process(map, out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return outFile;
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
禁止转载,如需转载请通过简信或评论联系作者。