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");
完美!
本文来自博客园,作者:void_main(),转载请注明原文链接:https://www.cnblogs.com/void--main/p/15396783.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)