XWPFTemplate(二)动态生成表格

时间:2024-02-23 09:55:15
public static void main(String[] args) throws IOException { //模板文件地址 String filePath = "/Users/liu/Downloads/test.docx"; Map<String,Object> map = new HashMap<>(); Calendar now = Calendar.getInstance(); //年 map.put("year", now.get(Calendar.YEAR)); //月 map.put("month", (now.get(Calendar.MONTH)) + 1); //日 map.put("day", now.get(Calendar.DAY_OF_MONTH)); List<Map<String,Object>> detailList=new ArrayList<>(); for (int i = 0; i < 3; i++) { Map<String,Object> detailMap = new HashMap<>(); detailMap.put("key",i); detailMap.put("key1","name"+i); detailMap.put("key2",i+"kg"); detailMap.put("key3",i); detailMap.put("key4",103.3); detailList.add(detailMap); } //图片 InputStream png = new FileInputStream("/Users/liu/Pictures/表情/7301626317522_.pic_hd.jpg"); map.put("png", new PictureRenderData(270, 270, PictureType.PNG, png)); List<HashMap> arrayList = new ArrayList<>(); for (int i = 0; i < 3; i++) { HashMap m = new HashMap(); m.put("image", Pictures.ofStream(new FileInputStream("/Users/liu/Pictures/表情/7301626317522_.pic_hd.jpg"), PictureType.PNG) .size(400, 400).create()); arrayList.add(m); } map.put("images",arrayList); //渲染表格 HackLoopTableRenderPolicy policy = new HackLoopTableRenderPolicy(); ConfigureBuilder configureBuilder = Configure.builder(); configureBuilder.bind("details", policy); Configure config = configureBuilder.build(); map.put("details", detailList); map.put("title","测试生成");//总金额 XWPFTemplate template = XWPFTemplate.compile(filePath, config).render(map); File file = new File("/Users/liu/Downloads/test1.docx"); FileOutputStream out = new FileOutputStream(file); template.write(out); out.close(); }