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 @   void_main()  阅读(1922)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示