EasyPoi简介
EasyPoi是一款基于Apache POI和jxls的Java开源框架,它可以用于快速创建Excel、Word、Pdf等复杂文档 。Easypoi最大的特点是可以通过注解来实现对Excel模板的自动填充,让用户不需要编写任何样式和格式代码就能够方便地导出各种数据格式的Excel文件 。Easypoi支持的功能非常强大,包括但不限于:
- 支持生成Excel模板,并使用注解快速填充数据 。
- 支持大部分Excel函数和公式 。
- 支持多级表头导出,支持合并单元格 。
- 支持自定义单元格样式、行高、列宽以及字体颜色等属性 。
- 支持数据导出前进行自定义处理,如数据转换、日期格式化等 。
- 支持设置Sheet页的名称、顺序、标签等属性 。
- 支持Excel的多种格式导入,如xls、xlsx和Csv等 。
实现Excel动态列导出
一般情况下,我们导出的Excel表头都是固定的 , 例如下面这样
但在某些业务需求中我们希望不要出生日期这一列 , 或者希望整个列头都是可以动态配置的,我们配置了什么字段,列头就展示什么字段,那么该如何实现呢?
EasyPoi官方也给了实现方案,下面通过一个例子演示:
环境依赖:
- SpringBoot
- EasyPoi
- 添加依赖
cn.afterturn easypoi-spring-boot-starter4.1.0 - 编写测试实体类
public class Student {private Stringname;private intsex;private Datebirthday;private Date registrationDate;}- 编写Web测试代码
@RestController@SpringBootApplicationpublic class ExcelDynamicColumnDemoApplication {private boolean needBirthday = true;public static void main(String[] args) {SpringApplication.run(ExcelDynamicColumnDemoApplication.class, args);}@GetMapping("dynamicColumnExport")public void dynamicClumnTest(HttpServletResponse response) throws IllegalAccessException {// 这里就可以根据自己的实际业务来配置自己的动态Excel表头了List columnList = new ArrayList<>();columnList .add(new ExcelExportEntity("学生姓名", "name"));columnList .add(new ExcelExportEntity("学生性别", "sex"));ExcelExportEntity exportEntity = new ExcelExportEntity("进校日期", "registrationDate");exportEntity.setFormat("yyyy-MM-dd");columnList .add(exportEntity);if(needBirthday){ExcelExportEntity exportEntity1 = new ExcelExportEntity("出生日期", "birthday");exportEntity1.setFormat("yyyy-MM-dd");columnList .add(exportEntity1);}List - 测试结果如下:

总结
最近在项目中遇到了需要动态配置Excel表头的需求 。虽然之前从网上找到了一些资料,但它们比较零散且有些不正确 。最终,在官网上找到了一个简单易懂的例子并成功实现了该功能 。在此将经验总结记录下来,以便日后参考 。官网文档地址:http://doc.wupaas.com/docs/easypoi/easypoi-1c0u4mo8p4ro8
