spring boot集成freemarker实现根据word模版生成文件并下载功能

spring boot集成freemarker实现根据word模版生成文件并下载功能

一、添加maven
    
        org.freemarker
        freemarker
        2.3.23
    
二、排除自动配置

启动类上添加@EnableAutoConfiguration(exclude = { FreeMarkerAutoConfiguration.class })注解。

三、制作模版

1.首先将word模版文档另存为xml格式文档。
2.再将xml模版文档后缀改为.ftl,例:test.xml改为test.ftl。
3.将文件放在spring boot 项目目录resources下的templates文件夹下。
spring boot集成freemarker实现根据word模版生成文件并下载功能_第1张图片
4.写入freemarker标签到模版需要替换的位置。
spring boot集成freemarker实现根据word模版生成文件并下载功能_第2张图片
如果有表格有动态数据,可以使用<#list>标签。
在这里插入图片描述

四、代码实现
      @Value("${web.upload-path}")
      private String uploadPath;//生成的文件存放的位置
     /**
     * exFileName:生成文件名称
     * fileType:生成文件类型,比如doc,xlsx
     * tempName:模版名称
     * map:替换的数据
     */
public void contractExport(String exFileName, String fileType, String tempName, Map<String, Object> map, HttpServletResponse response) {
     
        Configuration configuration = new Configuration();
        configuration.setDefaultEncoding("UTF-8");
        configuration.setTemplateLoader(new ClassTemplateLoader(PurchaseContractServiceImpl.class, "/templates/"));
        //获取需要导出的数据
        Map<String, Object> dataMap = map;
        Template t = null;
        try {
            String fileName = exFileName + "-" + System.currentTimeMillis() + "." + fileType;
            String tempPath = uploadPath;
            t = configuration.getTemplate(tempName); //要装载的模板
            File outFile = new File(tempPath + File.separator + fileName);
            if (!outFile.exists()) {
     
                outFile.createNewFile();
            }
            Writer out = null;
            FileOutputStream fos = null;
            fos = new FileOutputStream(outFile);
            OutputStreamWriter oWriter = new OutputStreamWriter(fos, "UTF-8");
            out = new BufferedWriter(oWriter);
            t.process(dataMap, out);
            out.close();
            fos.close();
            download(outFile, response);
        } catch (Exception e) {
     
            e.printStackTrace();
        }
    }

    /**
     * 下载生成的文件并删除临时文件
     */
    public void download(File file, HttpServletResponse response) {
     

        ServletOutputStream out = null;
        FileInputStream inputStream = null;
        try {
     
            String filename = file.getName();
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/DOWLOAD");
            response.setHeader("Content-Disposition", "attachment; filename=" +
                    String.valueOf(URLEncoder.encode(filename, "UTF-8")));
            out = response.getOutputStream();
            inputStream = new FileInputStream(file);
            byte[] buffer = new byte[512];
            int bytesToRead = -1;
            // 通过循环将读入的Word文件的内容输出到浏览器中
            while ((bytesToRead = inputStream.read(buffer)) != -1) {
     
                out.write(buffer, 0, bytesToRead);
            }
        } catch (Exception e) {
     
            e.printStackTrace();
        } finally {
     
            try {
     
                if (null != out) out.close();
                if (null != inputStream) inputStream.close();
                file.delete();
            } catch (Exception e2) {
     
                e2.printStackTrace();
            }
        }
    }
五、注意

1.替换数据map中key的值需要和模版总${xxxx}定义的值一致。
2.map中放的值不要为null,不然会报错。当然也可以在模版使用freemarker标签做null值的判断,这里就不说了,我也没太研究,感觉没必要。

你可能感兴趣的:(java,java,freemarker)