java使用velocity模板技术生成word
1.制作模板doc
2保存为xml
3用文本编辑工具打开xml,我这里用的notepad++,使用在线格式化工具格式化xml
https://c.runoob.com/front-end/710/(在线格式化xml)
格式化如图:把被分开的标签调整一下
表格的velocity循环标签插入和结束:
方法代码(我这里是返回了文件流,拿到文件流可以处理成自己想要的文件):
public static ByteArrayInputStream createDoc(VelocityContext vc, String templateurl, String templateName) throws Exception { ByteArrayInputStream in = null; try { Properties ps = new Properties(); ps.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, templateurl);// 这是模板所在路径 VelocityEngine ve = new VelocityEngine(); ve.init(ps); ve.init(); Template template = ve.getTemplate(templateName, "utf-8"); StringWriter swriter = new StringWriter(); template.merge(vc, swriter); swriter.flush(); swriter.close(); in = new ByteArrayInputStream(swriter.toString().getBytes("utf-8")); } catch (Exception e) { e.printStackTrace(); } return in; }
测试代码:
public static void main(String[] args) { //总的数据map VelocityContext allMap = new VelocityContext(); //标题 单个字段替换值 allMap.put("date", "20220917"); // 文件table数据汇总 List<ReportEntity> tableList = new ArrayList<ReportEntity>(); ReportEntity reportEntity = new ReportEntity(); reportEntity.setDjcs("1"); reportEntity.setDjsc(0); reportEntity.setTz("tz"); reportEntity.setYxl(20); tableList.add(reportEntity); //table第二条 ReportEntity reportEntity2 = new ReportEntity(); reportEntity2.setDjcs("1"); reportEntity2.setDjsc(0); reportEntity2.setTz("tz"); reportEntity2.setYxl(20); tableList.add(reportEntity2); allMap.put("table", reportEntity2); //调用方法 try { //我这是拿到了数据流/根据流直接输出或者转为文件保存都行 InputStream fis = VelocityUtil.createDoc(allMap, "E:\\", "test.xml"); //根据流处理输出还是生成文件 } catch (Exception e) { e.printStackTrace(); }
附 文件流操作:
直接响应前端的部分代码:
byte[] buffer = new byte[fis.available()]; fis.read(buffer); fis.close(); // 清空response response.reset(); String fileName = URLEncoder.encode("test.doc", CharsetUtil.UTF_8);//文件名带中文的话防止乱码 response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); response.setContentType("application/octet-stream;charset=UTF-8"); OutputStream toClient = new BufferedOutputStream(response.getOutputStream()); response.setContentType("application/octet-stream"); toClient.write(buffer); toClient.flush(); toClient.close();
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)