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");

 

 完美!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM