在我们平时工作中经常会遇到要操作Excel的功能,比如导出个用户信息或者订单信息的Excel报表。你肯定听说过POI这个东西,可以实现。但是POI实现的API确实很麻烦,它需要写那种逐行解析的代码(类似Xml解析)。今天给大家推荐一款非常好用的Excel导入导出工具EasyPoi,希望对大家有所帮助!

EasyPoi简介

用惯了SpringBoot的朋友估计会想到,有没有什么办法可以直接定义好需要导出的数据对象,然后添加几个注解,直接自动实现Excel导入导出功能?
EasyPoi正是这么一款工具,如果你不太熟悉POI,想简单地实现Excel操作,用它就对了!
EasyPoi的目标不是替代POI,而是让一个不懂导入导出的人也能快速使用POI完成Excel的各种操作,而不是看很多API才可以完成这样的工作。

集成

在SpringBoot中集成EasyPoi非常简单,只需添加如下一个依赖即可,真正的开箱即用!

  1. <dependency>
  2. <groupId>cn.afterturn</groupId>
  3. <artifactId>easypoi-spring-boot-starter</artifactId>
  4. <version>4.4.0</version>
  5. </dependency>

使用

接下来介绍下EasyPoi的使用,以会员信息和订单信息的导入导出为例,分别实现下简单的单表导出和具有关联信息的复杂导出。

简单导出

我们以会员信息列表导出为例,使用EasyPoi来实现下导出功能,看看是不是够简单!

  • 首先创建一个会员对象Member,封装会员信息;

    1. /**
    2. * 购物会员
    3. * Created by macro on 2021/10/12.
    4. */
    5. @Data
    6. @EqualsAndHashCode(callSuper = false)
    7. public class Member {
    8. @Excel(name = "ID", width = 10)
    9. private Long id;
    10. @Excel(name = "用户名", width = 20, needMerge = true)
    11. private String username;
    12. private String password;
    13. @Excel(name = "昵称", width = 20, needMerge = true)
    14. private String nickname;
    15. @Excel(name = "出生日期", width = 20, format = "yyyy-MM-dd")
    16. private Date birthday;
    17. @Excel(name = "手机号", width = 20, needMerge = true, desensitizationRule = "3_4")
    18. private String phone;
    19. private String icon;
    20. @Excel(name = "性别", width = 10, replace = {"男_0", "女_1"})
    21. private Integer gender;
    22. }
  • 在此我们就可以看到EasyPoi的核心注解@Excel,通过在对象上添加@Excel注解,可以将对象信息直接导出到Excel中去,下面对注解中的属性做个介绍;

    • name:Excel中的列名;
    • width:指定列的宽度;
    • needMerge:是否需要纵向合并单元格;
    • format:当属性为时间类型时,设置时间的导出导出格式;
    • desensitizationRule:数据脱敏处理,3_4表示只显示字符串的前3位和后4位,其他为*号;
    • replace:对属性进行替换;
    • suffix:对数据添加后缀。
  • 接下来我们在Controller中添加一个接口,用于导出会员列表到Excel,具体代码如下;

    1. /**
    2. * EasyPoi导入导出测试Controller
    3. * Created by macro on 2021/10/12.
    4. */
    5. @Controller
    6. @Api(tags = "EasyPoiController", description = "EasyPoi导入导出测试")
    7. @RequestMapping("/easyPoi")
    8. public class EasyPoiController {
    9. @ApiOperation(value = "导出会员列表Excel")
    10. @RequestMapping(value = "/exportMemberList", method = RequestMethod.GET)
    11. public void exportMemberList(ModelMap map,
    12. HttpServletRequest request,
    13. HttpServletResponse response) {
    14. List<Member> memberList = LocalJsonUtil.getListFromJson("json/members.json", Member.class);
    15. ExportParams params = new ExportParams("会员列表", "会员列表", ExcelType.XSSF);
    16. map.put(NormalExcelConstants.DATA_LIST, memberList);
    17. map.put(NormalExcelConstants.CLASS, Member.class);
    18. map.put(NormalExcelConstants.PARAMS, params);
    19. map.put(NormalExcelConstants.FILE_NAME, "memberList");
    20. PoiBaseView.render(map, request, response, NormalExcelConstants.EASYPOI_EXCEL_VIEW);
    21. }
    22. }
  • LocalJsonUtil工具类,可以直接从resources目录下获取JSON数据并转化为对象,例如此处使用的members.json

SpringBoot实现Excel导入导出Easypoi - 图1

  • 运行项目,直接通过Swagger访问接口,注意在Swagger中访问接口无法直接下载,需要点击返回结果中的下载按钮才行,访问地址:http://localhost:8088/swagger-ui/

SpringBoot实现Excel导入导出Easypoi - 图2

  • 下载完成后,查看下文件,一个标准的Excel文件已经被导出了。

SpringBoot实现Excel导入导出Easypoi - 图3

简单导入

导入功能实现起来也非常简单,下面以会员信息列表的导入为例。

  • 在Controller中添加会员信息导入的接口,这里需要注意的是使用@RequestPart注解修饰文件上传参数,否则在Swagger中就没法显示上传按钮了;

    1. /**
    2. * EasyPoi导入导出测试Controller
    3. * Created by macro on 2021/10/12.
    4. */
    5. @Controller
    6. @Api(tags = "EasyPoiController", description = "EasyPoi导入导出测试")
    7. @RequestMapping("/easyPoi")
    8. public class EasyPoiController {
    9. @ApiOperation("从Excel导入会员列表")
    10. @RequestMapping(value = "/importMemberList", method = RequestMethod.POST)
    11. @ResponseBody
    12. public CommonResult importMemberList(@RequestPart("file") MultipartFile file) {
    13. ImportParams params = new ImportParams();
    14. params.setTitleRows(1);
    15. params.setHeadRows(1);
    16. try {
    17. List<Member> list = ExcelImportUtil.importExcel(
    18. file.getInputStream(),
    19. Member.class, params);
    20. return CommonResult.success(list);
    21. } catch (Exception e) {
    22. e.printStackTrace();
    23. return CommonResult.failed("导入失败!");
    24. }
    25. }
    26. }
  • 然后在Swagger中测试接口,选择之前导出的Excel文件即可,导入成功后会返回解析到的数据。

SpringBoot实现Excel导入导出Easypoi - 图4

复杂导出

当然EasyPoi也可以实现更加复杂的Excel操作,比如导出一个嵌套了会员信息和商品信息的订单列表,下面我们来实现下!

  • 首先添加商品对象Product,用于封装商品信息;

    1. /**
    2. * 商品
    3. * Created by macro on 2021/10/12.
    4. */
    5. @Data
    6. @EqualsAndHashCode(callSuper = false)
    7. public class Product {
    8. @Excel(name = "ID", width = 10)
    9. private Long id;
    10. @Excel(name = "商品SN", width = 20)
    11. private String productSn;
    12. @Excel(name = "商品名称", width = 20)
    13. private String name;
    14. @Excel(name = "商品副标题", width = 30)
    15. private String subTitle;
    16. @Excel(name = "品牌名称", width = 20)
    17. private String brandName;
    18. @Excel(name = "商品价格", width = 10)
    19. private BigDecimal price;
    20. @Excel(name = "购买数量", width = 10, suffix = "件")
    21. private Integer count;
    22. }
  • 然后添加订单对象Order,订单和会员是一对一关系,使用@ExcelEntity注解表示,订单和商品是一对多关系,使用@ExcelCollection注解表示,Order就是我们需要导出的嵌套订单数据;

    1. /**
    2. * 订单
    3. * Created by macro on 2021/10/12.
    4. */
    5. @Data
    6. @EqualsAndHashCode(callSuper = false)
    7. public class Order {
    8. @Excel(name = "ID", width = 10,needMerge = true)
    9. private Long id;
    10. @Excel(name = "订单号", width = 20,needMerge = true)
    11. private String orderSn;
    12. @Excel(name = "创建时间", width = 20, format = "yyyy-MM-dd HH:mm:ss",needMerge = true)
    13. private Date createTime;
    14. @Excel(name = "收货地址", width = 20,needMerge = true )
    15. private String receiverAddress;
    16. @ExcelEntity(name = "会员信息")
    17. private Member member;
    18. @ExcelCollection(name = "商品列表")
    19. private List<Product> productList;
    20. }
  • 接下来在Controller中添加导出订单列表的接口,由于有些会员信息我们不需要导出,可以调用ExportParams中的setExclusions方法排除掉;

    1. /**
    2. * EasyPoi导入导出测试Controller
    3. * Created by macro on 2021/10/12.
    4. */
    5. @Controller
    6. @Api(tags = "EasyPoiController", description = "EasyPoi导入导出测试")
    7. @RequestMapping("/easyPoi")
    8. public class EasyPoiController {
    9. @ApiOperation(value = "导出订单列表Excel")
    10. @RequestMapping(value = "/exportOrderList", method = RequestMethod.GET)
    11. public void exportOrderList(ModelMap map,
    12. HttpServletRequest request,
    13. HttpServletResponse response) {
    14. List<Order> orderList = getOrderList();
    15. ExportParams params = new ExportParams("订单列表", "订单列表", ExcelType.XSSF);
    16. //导出时排除一些字段
    17. params.setExclusions(new String[]{"ID", "出生日期", "性别"});
    18. map.put(NormalExcelConstants.DATA_LIST, orderList);
    19. map.put(NormalExcelConstants.CLASS, Order.class);
    20. map.put(NormalExcelConstants.PARAMS, params);
    21. map.put(NormalExcelConstants.FILE_NAME, "orderList");
    22. PoiBaseView.render(map, request, response, NormalExcelConstants.EASYPOI_EXCEL_VIEW);
    23. }
    24. }
  • 在Swagger中访问接口测试,导出订单列表对应Excel;

SpringBoot实现Excel导入导出Easypoi - 图5

  • 下载完成后,查看下文件,EasyPoi导出复杂的Excel也是很简单的!

SpringBoot实现Excel导入导出Easypoi - 图6

自定义处理

如果你想对导出字段进行一些自定义处理,EasyPoi也是支持的,比如在会员信息中,如果用户没有设置昵称,我们添加下暂未设置信息。

  • 我们需要添加一个处理器继承默认的ExcelDataHandlerDefaultImpl类,然后在exportHandler方法中实现自定义处理逻辑;

    1. /**
    2. * 自定义字段处理
    3. * Created by macro on 2021/10/13.
    4. */
    5. public class MemberExcelDataHandler extends ExcelDataHandlerDefaultImpl<Member> {
    6. @Override
    7. public Object exportHandler(Member obj, String name, Object value) {
    8. if("昵称".equals(name)){
    9. String emptyValue = "暂未设置";
    10. if(value==null){
    11. return super.exportHandler(obj,name,emptyValue);
    12. }
    13. if(value instanceof String&&StrUtil.isBlank((String) value)){
    14. return super.exportHandler(obj,name,emptyValue);
    15. }
    16. }
    17. return super.exportHandler(obj, name, value);
    18. }
    19. @Override
    20. public Object importHandler(Member obj, String name, Object value) {
    21. return super.importHandler(obj, name, value);
    22. }
    23. }
  • 然后修改Controller中的接口,调用MemberExcelDataHandler处理器的setNeedHandlerFields设置需要自定义处理的字段,并调用ExportParamssetDataHandler设置自定义处理器;

    1. /**
    2. * EasyPoi导入导出测试Controller
    3. * Created by macro on 2021/10/12.
    4. */
    5. @Controller
    6. @Api(tags = "EasyPoiController", description = "EasyPoi导入导出测试")
    7. @RequestMapping("/easyPoi")
    8. public class EasyPoiController {
    9. @ApiOperation(value = "导出会员列表Excel")
    10. @RequestMapping(value = "/exportMemberList", method = RequestMethod.GET)
    11. public void exportMemberList(ModelMap map,
    12. HttpServletRequest request,
    13. HttpServletResponse response) {
    14. List<Member> memberList = LocalJsonUtil.getListFromJson("json/members.json", Member.class);
    15. ExportParams params = new ExportParams("会员列表", "会员列表", ExcelType.XSSF);
    16. //对导出结果进行自定义处理
    17. MemberExcelDataHandler handler = new MemberExcelDataHandler();
    18. handler.setNeedHandlerFields(new String[]{"昵称"});
    19. params.setDataHandler(handler);
    20. map.put(NormalExcelConstants.DATA_LIST, memberList);
    21. map.put(NormalExcelConstants.CLASS, Member.class);
    22. map.put(NormalExcelConstants.PARAMS, params);
    23. map.put(NormalExcelConstants.FILE_NAME, "memberList");
    24. PoiBaseView.render(map, request, response, NormalExcelConstants.EASYPOI_EXCEL_VIEW);
    25. }
    26. }
  • 再次调用导出接口,我们可以发现昵称已经添加默认设置了。

SpringBoot实现Excel导入导出Easypoi - 图7

总结

体验了一波EasyPoi,它使用注解来操作Excel的方式确实非常好用。如果你想生成更为复杂的Excel的话,可以考虑下它的模板功能。

参考资料

项目官网:https://gitee.com/lemur/easypoi

项目源码地址

https://github.com/macrozheng/mall-learning/tree/master/mall-tiny-easypoi