poi-tl的使用(最全详解)

官网地址

概述

poi-tl,简单的说,就是通过一些标记,如{{text}},{{@image}}等,放到你指定的word模板里,然后去读取替换这些值,再输出填充数据后的word,可以做生成报表的功能

一、引入pom

  <dependency>
            <groupId>com.deepoove</groupId>
            <artifactId>poi-tl</artifactId>
            <version>1.10.0</version>
        </dependency>

注意apache.poi版本要对应

 <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>4.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.1.2</version>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
            <version>4.1.2</version>
        </dependency>

二、准备工作

在D盘,自己创建两个文件夹,一个是用来存储模板文件,另一个是用来存储生成的文件
我这里是在D盘
D:\data\template 存放模板
D:\data\word 存放生成的文件

三、案例走起

案例一 :普通文本及图片的渲染
1.准备一个word模板,命名为test1.docx,放到D:\data\template 下

注意,{{}}是官方指定的格式,可以查看官网,当然也可以自定义,这个后面来讲
在这里插入图片描述

2.编写生成代码
    @PostMapping(value = "/testdoc01")
    public void Tx01() throws IOException {
        //存放要填充的数据
        Map<String, Object> datas = new HashMap<String, Object>();
        //模板地址
        String templateFilePath = "d:/data/template/";
        //生成文件的保存地址
        String destFilePath = "d:/data/template/word";
        
        //文字 这里介绍两种数据填充方式
        //1.可以设置一些通用样式
        Style style = Style.builder().buildUnderlineColor("00FF00").buildFontSize(18).buildColor("00FF00").build();
        datas.put("var1", Texts.of("内容1").style(style).create());
        datas.put("var2", Texts.of("超链接").link("http://deepoove.com").style(style).create());
        //2.文字可以通过Texts创建,也可以使用对象new TextRenderData("000000", "Sayi")
        datas.put("var3",new TextRenderData("000000", "内容3"));
        
        //图片
        datas.put("image", Pictures.ofUrl("http://deepoove.com/images/icecream.png")
                .size(100, 100).create());
       //渲染文件
        XWPFTemplate compile = XWPFTemplate.compile(templateFilePath + "test1.docx");
        compile.render(datas);
        //输出为文件,指定输出文件名
        compile.writeToFile(destFilePath+"out_test01.docx");
    }
3.调用后,查看生成的文件

在这里插入图片描述
在这里插入图片描述

案例二:表格的渲染,表格合并

1.准备一个word模板,命名为test2.docx,放到D:\data\template 下

在这里插入图片描述

2.编写生成代码
  @PostMapping(value = "/Tx02")
    public void Tx02() throws IOException {
        //存放要填充的数据
        Map<String, Object> datas = new HashMap<String, Object>();
           //模板地址
        String templateFilePath = "d:/data/template/";
        //生成文件的保存地址
        String destFilePath = "d:/data/template/word";

        //RowRenderData就是指定每一行数据的,可以去官网查阅,这里相当于设置了三行,row0就是表头,row1,row2是表内容
        RowRenderData row0 = Rows.of("姓名", "学历").textColor("FFFFFF")
                .bgColor("4472C4").center().create();
        RowRenderData row1 = Rows.create("李四", "博士");
        RowRenderData row2 = Rows.create("李四", "博士");
        datas.put("var1", Tables.create(row0, row1,row2));

        //合并单元格
        RowRenderData roW0 = Rows.of("列0", "列1", "列2", "列3").center().bgColor("4472C4").textColor("7F7f7F").textFontFamily("Hei").textFontSize(15).create();
        RowRenderData roW1 = Rows.create("没有数据", null, null, null);//第一行
        //合并第几行第几列 到 第几行第几列
        MergeCellRule rule = MergeCellRule.builder().map(MergeCellRule.Grid.of(1, 0), MergeCellRule.Grid.of(1, 2)).build();
        datas.put("var2", Tables.of(roW0, roW1).mergeRule(rule).create());
     
        //渲染文件
        XWPFTemplate compile = XWPFTemplate.compile(templateFilePath + "test2.docx");
        compile.render(datas);
        //输出为文件,指定输出文件名
        compile.writeToFile(destFilePath+"out_test2.docx");
    }
3.调用后,查看生成的文件

在这里插入图片描述

案例三:动态表格的生成

1.准备一个word模板,命名为test3.docx,放到D:\data\template 下

在这里插入图片描述

2.编写生成代码
        //模板地址
        String templateFilePath = "d:/data/template/";
        //生成文件的保存地址
        String destFilePath = "d:/data/template/word";
 		Map<String, Object> datas = new HashMap<String, Object>();
  
        Student student1 = new Student();
        student1.setAge("12");
        student1.setIndex("1");
        student1.setName("张三");
        student1.setSex("男");
        Student student2 = new Student();
        student2.setAge("122");
        student2.setIndex("11");
        student2.setName("张三1");
        student2.setSex("男1");
        List<Student> studentList = List.of(student1,student2);
        datas.put("lists",studentList);

		// 插件列表,可以去官网查看,有列循环,还有行循环,这里是行循环实例
        LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();
        
        //这里可以指定一个config类,用来指定一些规则,也可以改变模板中{{}}的这种格式
        Configure config = Configure.builder()
                .bind("lists", policy).build();
                
        XWPFTemplate compile = XWPFTemplate.compile(templateFilePath + "test3.docx",config);
        compile.render(datas);
        compile.writeToFile(destFilePath+"out_test3.docx");
3.调用后,查看生成的文件

在这里插入图片描述

案例四:结构体的应用

简述:结构体的应用,说白了,就是指定模板中的某一块内容,然后通过多个map,可以对这一块进行渲染,也就渲染出了多个这块的内容

1.准备一个word模板,命名为test4.docx,放到D:\data\template 下

在这里插入图片描述

2.编写生成代码
  @PostMapping(value = "/Tx03")
    public void Tx03() throws IOException {
        //模板地址
        String templateFilePath = "d:/data/template/";
        //生成文件的保存地址
        String destFilePath = "d:/data/template/word";
        Map<String,Object> map = new HashMap<>();

        Map<String,Object> map1 = new HashMap<>(){
            {
                put("tex1","hhhhh11");
            }
        };

        Map<String,Object> map2 = new HashMap<>(){
            {
                put("tex1","hhhhh22");
            }
        };


        List<Map<String,Object>> maps = Arrays.asList(map1,map2);
        map.put("tests",maps);
        map.put("tex2","哈哈");

        ConfigureBuilder builder = Configure.builder();
        XWPFTemplate compile = XWPFTemplate.compile(templateFilePath + "test4.docx",builder.build());
        compile.render(map);
        compile.writeToFile(destFilePath+"out_test4.docx");
    }
3.调用后,查看生成的文件

在这里插入图片描述
以上就是一些简单的例子了,上面都是输出的文件,当然也可以已流的形式输出,用于文件下载
只需要修改一个地方

在这里插入图片描述

五、结构体应用升级版,使用对象作为数据源

1.准备一个word模板,命名为test4.docx,放到D:\data\template 下
在这里插入图片描述

在这里插入图片描述

2.编写生成代码

渲染的对象

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class WarningData {

    private List<ExperienceData> experiences;

}

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class ExperienceData {

    private String title;

    private String error;

//渲染图片的对象
    private PictureRenderData pictureRenderData;
}

这里就是封装的传入参数,warningData就是上面的对象

    default void generateWordStream(ServletOutputStream outputStream, String templateFilePath, Object WarningData ) throws IOException {

        File file = new File(templateFilePath);
        if(!file.isFile())
            throw new BizException(CodeMsg.FILE_NOT_EXIST_ERROR.fillArgs("模板文件不存在!"+file.isFile()+"  "+templateFilePath));

        ConfigureBuilder configureBuilder = Configure.builder();

        XWPFTemplate.compile(templateFilePath,configureBuilder.build())
                .render(WarningData)
                .write(outputStream);
    }
  • 32
    点赞
  • 166
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 31
    评论
首先,你需要在你的项目中添加poi-tl的依赖,如果你使用Maven,可以在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>com.deepoove</groupId> <artifactId>poi-tl</artifactId> <version>1.3.1</version> </dependency> ``` 如果你使用Gradle,可以在build.gradle文件中添加以下依赖: ``` compile 'com.deepoove:poi-tl:1.3.1' ``` 添加依赖后,你就可以开始使用poi-tl了。poi-tl是一个基于Apache POI的模板引擎,可以用来生成Word、Excel、PowerPoint等文档。下面是一个简单的示例,演示如何使用poi-tl生成一个Word文档: ```java import com.deepoove.poi.XWPFTemplate; import com.deepoove.poi.data.*; import com.deepoove.poi.data.style.Style; import com.deepoove.poi.util.BytePictureUtils; import java.io.FileOutputStream; import java.io.IOException; import java.util.*; public class PoiTlDemo { public static void main(String[] args) throws IOException { // 创建模板数据 Map<String, Object> data = new HashMap<>(); data.put("title", "poi-tl示例"); data.put("name", "张三"); data.put("age", 28); List<Map<String, Object>> list = new ArrayList<>(); list.add(createDataMap("项目一", "2019-01-01", "2019-02-01")); list.add(createDataMap("项目二", "2019-03-01", "2019-04-01")); data.put("list", list); // 创建模板 DocxRenderData template = new DocxRenderData( PoiTlDemo.class.getResourceAsStream("/template.docx"), data); // 渲染模板 XWPFTemplate document = XWPFTemplate.compile(template).render(data); // 将生成的文档保存到本地 FileOutputStream out = new FileOutputStream("output.docx"); document.write(out); out.close(); // 关闭文档 document.close(); } private static Map<String, Object> createDataMap(String name, String startDate, String endDate) { Map<String, Object> dataMap = new HashMap<>(); dataMap.put("name", name); dataMap.put("startDate", startDate); dataMap.put("endDate", endDate); return dataMap; } } ``` 上面的代码中,我们首先创建了一个模板数据,包含了一个标题、一个姓名、一个年龄和一个项目列表。然后,我们创建了一个模板,使用了一个Word文档作为模板文件,将模板数据传递给了模板。最后,我们使用XWPFTemplate.compile()方法编译模板,并使用render()方法渲染模板,得到了一个XWPFTemplate对象,将其保存到本地文件,并关闭了文档。 这只是poi-tl的一个简单示例,如果你想深入了解poi-tl的更多用法,请查看官方文档。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 31
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JavaSupeMan

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值