关键对象:Poi-tl Documentation
学习路径:http://deepoove.com/poi-tl/#_why_poi_tl
代码Demo:
public static void main(String[] args) { HashMap<String, Object> dataMap = new HashMap<>(); Map<String, Object> data = new HashMap<String, Object>(); ArrayList<Map<String, Object>> dataList = new ArrayList<>(); //封装数据 data.put("username", "demo"); data.put("password", "001"); data.put("head", Pictures.ofLocal("C:\\Users\\Pictures\\Saved Pictures\\ais.jpg") .size(35, 35).create()); dataList.add(data); //key要和模板中的开始结束标签保持一致 dataMap.put("wordExportTemp", dataList); try { String res = wordUtil.tempRender(dataMap); System.out.println(res); } catch (Exception e) { System.out.println("Fail"); } }
public class wordUtil { public static String tempRender(HashMap<String, Object> dataMap) throws Exception { //模板文件 String inPut = "D:\\tempword\\data\\wordFile.docx"; //生成文件 String outPut = "D:\\tempword\\data\\2021-09-15\\exportWord.docx"; //获取模板文件数据 XWPFWordExtractor extractor = new XWPFWordExtractor(OPCPackage.open(new FileInputStream(inPut))); //获取String型模板数据 System.out.println(extractor.getText()); FileOutputStream outputStream = new FileOutputStream(outPut); //用来 ConfigureBuilder builder = Configure.builder(); //用默认的方式抛出异常 builder.useDefaultEL(true); //匹配除了标签前后缀外的任意字符 builder.buildGrammerRegex(RegexUtils.createGeneral("{{", "}}")); //创建结果对象 XWPFTemplate docx = XWPFTemplate.compile(inPut,builder.build()); //数据渲染 docx.render(dataMap); //数据写出 docx.write(outputStream); outputStream.flush(); outputStream.close(); docx.close(); return "OK"; } }
模板:
注意:{{?wordExportTemp}} 中的“wordExportTemp”要和封装数据Map的“key"保持一致!
结果