摘要
为了实现一个可以自定义word模板并生成word文档的功能,我调研了当前市面上的几个工具包,综合研究比较后,决定选用poi-tl来实现这个功能。poi-tl是一个基于Apache POI的Word模板引擎,也是一个免费开源的Java类库,可以非常方便的加入到你的项目中,并且拥有着让人喜悦的特性,它拥有功能强大的插件,使用Word模板和数据创建很棒的Word文档。通过以下示例我们实现了使用网络上的word模板、本地word模板;表格行动态生成;填充图片;多选框生成,空选和选中;列表生成。
一、环境
- Windows 10
- office word 2019
- java11
二、标签
poi-tl是一种无逻辑「logic-less」的模板引擎,没有复杂的控制结构和变量赋值,只有标签。标签由前后两个大括号组成,{ {title}}是标签,{ {?title}}也是标签,title是这个标签的名称,问号标识了标签类型,接下来我们来看看有哪些默认标签类型(用户可以创建新的标签类型,这属于更高级的话题)。
文本
{ {var}}
图片
{ {@var}}
表格
{ {#var}}
列表
{ {*var}}
三、使用步骤
引入依赖
implementation 'com.deepoove:poi-tl:1.12.1'
我们使用的word模板
生成的结果
码代码
@Test
void contextLoads() throws IOException {
Referrer goods1 = new Referrer();
goods1.name = "弗兰德";
goods1.count = 3;
Referrer goods2 = new Referrer();
goods2.name = "伯恩斯";
goods2.count = 10;
List<Referrer> goodsList = new ArrayList<>();
goodsList.add(goods1);
goodsList.add(goods2);
LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();
// 使用循环表格行生成的插件
Configure config = Configure.builder()
.bind("referrer", policy).build();
// 从URL获取输入流
// URL url = new URL("https://file.server.xxxx.cn/%E9%99%84%E42%E8%81%94%E7%BD%91%E4%B8%93%E4%B8%9A%E6%9C%8D%E5%A1%A8.docx");
// InputStream is = url.openStream();
// 创建Word模板对象
// XWPFTemplate template = XWPFTemplate.compile(is, config);
// 从磁盘获取word模板文件
File file = new File("D://temp/poidemo.docx");
XWPFTemplate template = XWPFTemplate.compile(file, config);
template.render(
new HashMap<String, Object>(){
{
put("name", "侯莫");
put("familyName", "辛普森");
put("photo1", "https://bkimg.cdn.bcebos.com/pic/279759ee3d6d55fbae3c50b56b224f4a21a4ddae");
put("referrer", goodsList);
put("codeboy", new TextRenderData("R", new Style("Wingdings 2", 14)));
put("designer", new TextRenderData("\u25A1", new Style("Wingdings 2", 14)));
put("npdp", new TextRenderData("\u25A1", new Style("Wingdings 2", 14)));
put("pmp", new TextRenderData("R", new Style("Wingdings 2", 14)));
put("list11", Numberings.create("Plug-in grammar",
"Supports word text, pictures, table...",
"Not just templates"));
}});
template.writeAndClose(new FileOutputStream("output.docx"));
}
}