poi-tl 批量导出文件
poi-tl它官方没有批量导出文件的方法,在工作过程中使用过两种方法导出多个图片:
1、直接在模板中写多个文件导出的标签
2、使用表格进行导出
在模板中写多个文件导出标签
这个方式的好处是简单,对于整个项目中只有几个固定的图片的图片,或者有图片最大的限制情况下使用。
具体的使用其实很简单,我们导出一个文件使用 {{@imgPath}} ,我们在导出的时候把每个图片的后面加上一个序列号,然后我们直接在模板中写到最大的图片序号,如果没有对应的图片地址,那么就会是空的,如果有的话就会进行插入,具体实现代码部分:
// imgArr 为图片地址数组
Map<String, Object> imgMap = new new HashMap<String, Object>();
for(int i = 0 ; i < imgArr.size() ; i++){
imgMap.put("imgPath" + i, imgArr.get(i));
}
XWPFTemplate template = XWPFTemplate.compile("D:\template.docx").render(imgMap);
try {
template.writeAndClose(new FileOutputStream("D:\out.docx"));
}catch (Exception e){
e.printStackTrace();
}
假如有十张图片的情况下模板部分:
如果当图片没有十个的情况下只会显示有图片的部分,没有的部分不进行显示,也不会报错.
使用表格进行导出
poi-tl 支持表格导出,那么我们可以在表格的数组中存图片的路径,然后使用表格的写法+图片的写法实现动态导出表格,代码部分:
List<String> imgPathArr = new ArrayList();
ConfigureBuilder configureBuilder = Configure.builder();
LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();
// 声明是数组对象 否则模板中用不了
if( null != arr ) {
imgPathArr.stream().forEach(str -> {
configureBuilder.bind(str, policy);
});
}
Map<String, Object> imgMap = new new HashMap<String, Object>();
imgMap.put("imgPathArr",imgPathArr);
XWPFTemplate template = XWPFTemplate.compile("D:\template.docx").render(imgMap);
try {
template.writeAndClose(new FileOutputStream("D:\out.docx"));
}catch (Exception e){
e.printStackTrace();
}
按照上面这样就可以标识 imgPathArr 是一个表格,同时我们在里面存储的是图片的地址,我们模板中这样进行使用就可以了: