目录
关于poi-tl
关于poi-tl区块对
poi-tl中分页符如何表示
实现的例子
准备文档模板
实现的代码
测试结果
总结
关于poi-tl
poi-tl是基于Apache POI的Word模板引擎,它使用java语言来实现,它可以将word文档中的“标签”渲染为用户指定的文字、表格、图片等。使用模板引擎生成word比使用Apache POI的API来生成来说,快捷了不少。关于poi-tl的具体介绍请看poi-tl作者网站。相信能够进来阅读博客的朋友都对此有一定了解的。
关于poi-tl区块对
这里直接引用poi-tl作者的原话,“区块对由前后两个标签组成,开始标签以?标识,结束标签以/标识:{{?sections}}{{/sections}}”。
区块对的作用之一是可以遍历java集合(java.util.Collection),将集合内的内容渲染为用户指定的对象。如:
应用场景一:在一个文档中动态生成段落文本及图片。
应用场景二:用户想在同一个批量生成一些样式重复、内容不同的表格,可以使用区块对来实现。
poi-tl中分页符如何表示
最简单的方法就是直接在word模板中插入分页符。但是这种方式不太灵活,比如说在动态生成段落时,有些段落结尾后,需要分页,而有些段落不需要分页。
基于此情况,本人认为应该使用布尔值结合Apache POI的API来生成分页符。在POI中org.apache.poi.xwpf.usermodel.XWPFRun类有插入分页符的方法addBreak。而在poi-tl中使用POI的API一般来说需要结合自定义插件(即实现com.deepoove.poi.policy.AbstractRenderPolicy)。
实现的例子
准备文档模板
如下
实现的代码
这里为了便于测试,将所有类和方法都写在一个文件中。
import com.deepoove.poi.XWPFTemplate;import com.deepoove.poi.config.Configure;import com.deepoove.poi.policy.AbstractRenderPolicy;import com.deepoove.poi.render.RenderContext;import org.apache.poi.xwpf.usermodel.BreakType;import org.apache.poi.xwpf.usermodel.XWPFRun;import java.io.IOException;import java.util.ArrayList;import java.util.HashMap;import java.util.List;/*** poi-tl中自定义插入分页符标签的例子,不可直接用于生产环境**/public class PageBreakTest {static String templatePath = "E:\\测试.docx";public static void main(String[] args) throws IOException {pageBreakDemo("E:\\测试输出.docx");}public static void pageBreakDemo(String outPut) throws IOException {List<MyParagraph> wordDataList = new ArrayList<>();//生成数据setWordDataList(wordDataList);//这里绑定了一个自定义的插件到isPageBreak标签Configure config = Configure.builder().useSpringEL().bind("isPageBreak", new AbstractRenderPolicy<Boolean>() {@Overridepublic void doRender(RenderContext<Boolean> context) throws Exception {XWPFRun where = context.getWhere();boolean thing = context.getThing();where.setText("", 0);if (thing)where.addBreak(BreakType.PAGE);}}).build();pile(templatePath, config).render(new HashMap<String, Object>() {{put("paragraphList", wordDataList);}}).writeToFile(outPut);}/*** 生成测试数据* @param wordDataList*/private static void setWordDataList(List<MyParagraph> wordDataList){wordDataList.add(new MyParagraph("明月几时有,把酒问青天。",false));wordDataList.add(new MyParagraph("不知天上宫阙,今夕是何年?",false));wordDataList.add(new MyParagraph("我欲乘风归去,又恐琼楼玉宇,高处不胜寒。",true));wordDataList.add(new MyParagraph("大江东去,浪淘尽,千古风流人物。",false));}}/*** 测试实体类*/class MyParagraph {private String content;private Boolean isPageBreak;public MyParagraph(String content, Boolean isPageBreak) {this.content = content;this.isPageBreak = isPageBreak;}public MyParagraph() {}public String getContent() {return content;}public void setContent(String content) {this.content = content;}public Boolean getIsPageBreak() {return isPageBreak;}public void setIsPageBreak(Boolean pageBreak) {isPageBreak = pageBreak;}}
测试结果
这里使用word大纲模式展示
总结
实现在poi-tl中用自定义的布尔值在word文档中插入分页符,实现的核心还是在poi-tl中实现自定义插件。因为有自定义插件的存在,也使得poi-tl生成文档变得更加灵活。