java poi-tl word模板填充
前言
word填充基于com.deepoove 的 poi-tl
一、引入maven库
注意:版本对应 poi-tl 版本 1.9.0 对应 apache poi 版本 4.1.2
代码如下(示例):
<!--word模板数据解析-->
<dependency>
<groupId>com.deepoove</groupId>
<artifactId>poi-tl</artifactId>
<version>1.9.0</version>
</dependency>
二、读入数据
采用${key}的形式进行填充!默认是{{key}}的格式
原word模板:
效果图:
三、示例代码
代码如下(示例):
public static void main(String[] args) throws Exception{
resolveTemp();
}
public static File resolveTemp() throws Exception {
String path = System.getProperty("user.dir") + "/file";
Map<String, Object> datas = new HashMap<>();
datas.put("dept", "采购部");
datas.put("name", "张三");
LocalDate date = LocalDate.now();
datas.put("year", date.getYear());
datas.put("month", date.getMonthValue());
datas.put("day", date.getDayOfMonth());
List<Map<String, Object>> itemList = new ArrayList<>();
Map<String, Object> itemMap = new HashMap<>();
itemMap.put("goods", "笔记本电脑");
itemMap.put("num", "2");
itemMap.put("cost", "10000");
itemMap.put("remark", "按需采购");
itemList.add(itemMap);
itemMap = new HashMap<>();
itemMap.put("goods", "台式电脑");
itemMap.put("num", "1");
itemMap.put("cost", "8000");
itemMap.put("remark", "按需采购");
itemList.add(itemMap);
datas.put("item", itemList);
datas.put("total", "18000.00");
//读取图片
File file = new File(path + "/1.png");
BufferedImage bi = ImageIO.read(file);
int width = bi.getWidth();
//源图高度
int height = bi.getHeight();
datas.put("image", new PictureRenderData(width, height, PictureType.PNG, new FileInputStream(file)));
System.out.println("datas = " + datas);
HackLoopTableRenderPolicy hackLoopTableRenderPolicy = new HackLoopTableRenderPolicy();
Configure config = Configure.builder()
.buildGramer("${", "}")//此处可以变更原模板{{}}
.bind("item", hackLoopTableRenderPolicy)//标记表格参数
.build();
String sourceFile = path + "/template/采购单.docx";
String docNow = LocalDateTimeUtils.formatDate(date, "yyyy年MM月dd日");
String targetFile = path + "/order/采购单" + docNow + ".docx";
XWPFTemplate template = XWPFTemplate.compile(new FileInputStream(sourceFile), config).render(datas);
File wordFile = new File(targetFile);
File parentFile = wordFile.getParentFile();
if (!parentFile.exists()) {
parentFile.mkdirs();
}
FileOutputStream out = new FileOutputStream(wordFile);
template.write(out);
out.flush();
out.close();
template.close();
return wordFile;
}
总结
以上就是今天要讲的内容,本文仅仅简单介绍了poi-tl的使用,喜欢就点个赞吧!