java使用freemarker通过模板导出word(基于若依)

1.创建word模板,用英文字段代替需要插入数据的位置

 

 

 

 2.另存为xml格式,注:最好是用office另存为word2003xml 兼容性更强

 

 

3.在resources目录下建立目录templates 并把文件拖入,修改后缀名为ftl

 

 

4.在idea中打开,利用Ctrl+R 替换字段,用${}把字段包裹起来

 

 

 

 

 

 5.编写工具类

public class WordUtil {
    private static Configuration configuration = null;
    static {
        configuration = new Configuration();
        configuration.setDefaultEncoding("utf-8");
        configuration.setClassForTemplateLoading(WordUtil.class, "/templates");
    }

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

    public static AjaxResult exportMillCertificateWord( Map map, String title, String ftlFile) throws IOException {
        Template freemarkerTemplate = configuration.getTemplate(ftlFile);
            String fileName = UUID.randomUUID().toString() + "_" + title + ".doc";
            String downloadPath = RuoYiConfig.getDownloadPath() + fileName;
            File desc = new File(downloadPath);
            if (!desc.getParentFile().exists())
            {
                desc.getParentFile().mkdirs();
            }
            // 调用工具类的createDoc方法生成Word文档
             createDoc(map,freemarkerTemplate,downloadPath);
            return AjaxResult.success(fileName);
    }

    private static File createDoc(Map<?, ?> dataMap, Template template,String name) {
        File f = new File(name);
        Template t = template;
        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;
    }
}

6.调用方法 查看结果

     Map map = new HashMap();
        map.put("aa","张三");
        map.put("bb","2021年10月12日");
        map.put("cc","1");
        return WordUtil.exportMillCertificateWord(map,"offer","test.ftl");

 

 完美!

posted @ 2021-10-12 10:46  void_main()  阅读(2125)  评论(0)    收藏  举报