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");
完美!