poi-tl是一款很是好用的word模板生成库,更新响应快、文档demo齐全。堪称word模板界的小军刀!html
若是你对word模板技术有了解、或者有兴趣,更甚者工做中接触过,那么接下来的内容应该会让你有所收获。java
功能以下:git
更多文档参考以下:poi-tlgithub
这里再也不更多的赘述poi-tl的功能了,很是优秀的一个word模板库。spring
若是你还没使用过poi-tl,那么接下来的内容,你应该不太会感同身受。express
poi-tl使用一段时间后会发现仍存在一些问题,好比行列表格须要本身写代码指定样式、图片须要写代码指定高度宽度、列表也写代码指定样式。数组
为最大化利用word的样式,减小代码量,这里在v1.6.0之上进行源码扩展。测试
加入模板语法:name|attr:var
。加密
fork地址:githubspa
语法:{{table|limit:var}}
模板:
其中:
{{table|5:[users]}}
,表明了这是一个表格模板(能够出如今表格的任意位置,建议在表头),users
则说明数据中存在一个 users 的 key 。测试代码:
@Test public void run() { Path path = Paths.get("src/test/resources", "table_pattern.docx"); XWPFTemplate template = XWPFTemplate.compile(path.toFile()) // 数据 .render(new HashMap<String, Object>() {{ put("users", Arrays.asList(new User("张三", 1), new User("李四", 2))); }}); // 输出 Path outPath = Paths.get("src/test/resources", "table_pattern_out.docx"); try (OutputStream os = new BufferedOutputStream(new FileOutputStream(outPath.toFile()))) { template.write(os); } catch (IOException e) { LOG.error("render tpl error", e); } finally { try { template.close(); } catch (IOException e) { LOG.error("close template error", e); } } }
能够看到这里的 map 中存在 users 这个 key,且存在 2 条数据。User 这个对象有两个属性 name、age ,模板在解析时,会自动取值。
输出:
总结:表格正常渲染,并且样式也正常保留,原来的数据也会保留下来,数据不足补空行。
语法:{{image|height*width:var}}
模板:
测试代码:
@Test public void run() throws IOException { Path logoPath = Paths.get("src/test/resources", "logo.png"); byte[] bytes = Files.readAllBytes(logoPath); byte[] encode = Base64.getEncoder().encode(bytes); Path path = Paths.get("src/test/resources", "image_pattern.docx"); XWPFTemplate template = XWPFTemplate.compile(path.toFile()) // 数据 .render(new HashMap<String, Object>() {{ put("logo", new String(encode)); }}); // 输出 Path outPath = Paths.get("src/test/resources", "image_pattern_out.docx"); try (OutputStream os = new BufferedOutputStream(new FileOutputStream(outPath.toFile()))) { template.write(os); } catch (IOException e) { LOG.error("render tpl error", e); } finally { try { template.close(); } catch (IOException e) { LOG.error("close template error", e); } } }
输出:
总结:图片能正常根据高度宽度渲染出来
语法:list|limit:var
模板:
测试代码:
@Test public void run() { Path inPath = Paths.get("src/test/resources", "list_pattern.docx"); Path outPath = Paths.get("src/test/resources", "list_pattern_out.docx"); Map<String, Object> model = new HashMap<String, Object>() {{ put("items", Arrays.asList("张三", "李四", "王五")); }}; try (InputStream is = Files.newInputStream(inPath); OutputStream os = Files.newOutputStream(outPath)) { Tpl.render(is, model).out(os); } catch (IOException e) { LOG.info("render tpl failed", e); } }
输出:
总结:列表也能正常渲染,保证原有的格式。
看示例,你也许会以为很奇怪,为何语法明明写的var
,可是截图中有的写的是[var]
、有的却写的var
。
这是由于变量取值采用的 spring expression 语法:若是代码中是一个对象,就能够直接写var
,是一个map,就写[var]
,数组则是var[下标]
。
若是以为有用,快快使用起来吧!
原文出处:https://www.cnblogs.com/bener/p/12028952.html