FreeMarker的入门使用

liuqiang 2021年05月08日 6次浏览

引入依赖

maven中介仓库

<!-- https://mvnrepository.com/artifact/org.freemarker/freemarker -->
<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.30</version>
</dependency>

或者

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>

java-web 生成word样例

@RequestMapping(path="/test",produces="application/msword;charset=UTF-8")
    public void  test(HttpServletRequest request, HttpServletResponse resp) {
        File file = null;
        InputStream fin = null;
        ServletOutputStream out = null;
        Map<String,Object> map = Maps.newHashMap();
        map.put("prjName","N999-测试");
        try {
            // 调用工具类WordGenerator的createDoc方法生成Word文档
            file = FreeMarkerGenerator.createDoc(map, "");

            fin = new FileInputStream(file);

            //resp.setCharacterEncoding("utf-8");
             //resp.setContentType("application/msword");
            // 设置浏览器以下载的方式处理该文件默认名为resume.doc
            resp.addHeader("Content-Disposition", "attachment;filename=resume.doc");

            out = resp.getOutputStream();
            byte[] buffer = new byte[512];	// 缓冲区
            int bytesToRead = -1;
            // 通过循环将读入的Word文件的内容输出到浏览器中
            while((bytesToRead = fin.read(buffer)) != -1) {
                out.write(buffer, 0, bytesToRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            if (fin != null){
                try {
                    fin.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                if(file != null){
                    // 删除临时文件
                    file.delete();
                }

            }
        }

   private String fileNameHandle(HttpServletRequest request, String fileName) throws IOException{
        String userAgent = request.getHeader("User-Agent");
        byte[] bytes = userAgent.contains("MSIE") ? fileName.getBytes() : fileName.getBytes("UTF-8");
        // 各浏览器基本都支持ISO编码
        String name = new String(bytes, "ISO-8859-1");
        return name;
    }

    }

public class FreeMarkerGenerator {

    private static Configuration configuration = null;
    private static Map<String, Template> allTemplates = null;

    static {
        configuration = new Configuration(Configuration.VERSION_2_3_30);
        configuration.setDefaultEncoding("utf-8");
        configuration.setClassForTemplateLoading(FreeMarkerGenerator.class, "/template/");
        allTemplates = new HashMap<>();
        try {
            allTemplates.put("资管四部保险金信托信托管理报告", configuration.getTemplate("资管四部保险金信托信托管理报告.ftl"));
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    private FreeMarkerGenerator() {
        throw new AssertionError();
    }

    /**
     *  生成docx
     * @param dataMap
     * @param type
     * @return
     */
    public static File createDoc(Map<?, ?> dataMap, String type) {
        String name = "temp" + (int) (Math.random() * 100000) + ".docx";
        File f = new File(name);
        Template t = allTemplates.get(type);
        try {
            // 这个地方不能使用FileWriter因为需要指定编码类型否则生成的Word文档会因为有无法识别的编码而无法打开
            Writer w = new OutputStreamWriter(new FileOutputStream(f), "utf-8");
            t.process(dataMap, w);
            w.close();
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new RuntimeException(ex);
        }
        return f;
    }




}

根据模板doc 制作生成目标doc:

doc模板填充 ${} -->另存为 open2003xml -> 格式化xml,修改${}处的错乱格式 -->修改后缀为ftl