word模板引擎poi-tl保姆级使用教程

1.poi-tl简介

poi-tl是一个基于Apache POI的Word模板引擎,也是一个免费开源的Java类库(官方文档: Poi-tl Documentation)

2.poi-tl特性

1.支持注入的模板类型

  • 文本

  • 图片

  • 列表

  • 区块对

  • 嵌套

  • 多系列图表

  • 单系列图表

  • 组合图表

2.poi-tl使用步骤
1.引入依赖
<dependency>
  <groupId>com.deepoove</groupId>
  <artifactId>poi-tl</artifactId>
  <version>1.12.0</version>
</dependency>
2.核心使用代码
XWPFTemplate template = XWPFTemplate.compile("template.docx").render(
  new HashMap<String, Object>(){
  {
    put("title", "Hi, YC");
}});  
​
template.writeAndClose(new FileOutputStream("output.docx"));

3.常用方法
XWPFTemplate template = XWPFTemplate.compile("filePath");  // 编译模板
template.render(填充的数据map或对象)      //渲染数据
template.write(输出流out)               //输出到流
4.具体实现

1.构建word模板

模板中填充位置占位符语法: { {name}}

2.引入模板

XWPFTemplate template = XWPFTemplate.compile("filePath")

3.模板中填充数据类型

3.1 Map: 键为占位符名称, 值为填充的具体数据

3.2 对象: 对象中的属性为占位符名称

4.构建word文件并导出

        // 数据转换
        Map<String, Object> fillMap = new HashMap<>();
        // 文件名称
        String fileName = URLEncoder.encode("文件名称", StandardCharsets.UTF_8);
        // 指示响应内容的格式
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".docx");
​
        try (OutputStream out = response.getOutputStream();
             XWPFTemplate template = getTemplate(filePath)) {
​
            // 数据填充
            template.render(fillMap);
            template.write(out);
            out.flush();
        } catch (IOException ex) {
            throw new IOException(ex);
        }
3.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值