使用EasyPoi实现多Sheet页导出的示例代码

 更新时间:2025年03月08日 15:55:42   作者:chenHelloWorld  
在项目开发中,我们常常会遇到导出多Sheet页的需求,本文降维打击介绍一下如何使用EasyPoi实现这一功能,文中的示例代码简洁易懂,有需要的可以参考下

前言

因多次遇到导出多Sheet页的需求,故记录下来,以备后续参考使用

一、Pom依赖

<!-- 集成easypoi组件 .导出excel http://easypoi.mydoc.io/ -->
            <dependency>
                <groupId>cn.afterturn</groupId>
                <artifactId>easypoi-base</artifactId>
                <version>3.2.0</version>
            </dependency>
            <dependency>
                <groupId>cn.afterturn</groupId>
                <artifactId>easypoi-web</artifactId>
                <version>3.2.0</version>
            </dependency>
            <dependency>
                <groupId>cn.afterturn</groupId>
                <artifactId>easypoi-annotation</artifactId>
                <version>3.2.0</version>
            </dependency>

二、主方法

SXSSFWorkbook workbook = new SXSSFWorkbook();
try {
                workbook = this.getSheetsList(notQualifiedSumDeptCountVos, locale);
                return workbook;
            } catch (Exception e) {
                log.error("错误",e);
                return null;
            }

三、拼接多Sheet页

private SXSSFWorkbook getSheetsList(List<Vo> notQualifiedSumDeptCountVos, Locale locale){
        // 点检项排名导出多sheet页
        List<Map<String, Object>> sheetsList = new ArrayList<>();
        // 创建数据概览1-不合格次数的sheet
        this.getNotQualifiedSumExportSheet(notQualifiedSumDeptCountVos, sheetsList, locale);
        SXSSFWorkbook workbook = ExcelUtils.exportExcel(sheetsList);
        return workbook;
    }

四、获取单个Sheet页

private void getNotQualifiedSumExportSheet(List<NotQualifiedSumDeptCountVo> notQualifiedSumDeptCountVos, List<Map<String, Object>> sheetsList, Locale locale){
        if (CollectionUtil.isNotEmpty(notQualifiedSumDeptCountVos)) {
            // 创建数据概览1-不合格次数的sheet使用的map
            Map<String, Object> notQualifiedSumExportMap = new HashMap<>(16);
            String notQualifiedSumTitle = messageSource.getMessage("export.check.item.rank0.not.qualified.sum.title", null, locale);
            String notQualifiedSumSheetName = messageSource.getMessage("export.check.item.rank.not.qualified.sheet.name", null, locale);
            ExportParams notQualifiedSumExportParams = new ExportParams(notQualifiedSumTitle, notQualifiedSumSheetName, ExcelType.XSSF);
            List<ExcelExportEntity> notQualifiedSumColList = new ArrayList<>();
            List<Map<String,Object>> notQualifiedSumResList = new ArrayList<>();
            try {
                ExcelUtils.getExcelExportMap(notQualifiedSumColList, notQualifiedSumResList, notQualifiedSumDeptCountVos, NotQualifiedSumDeptCountVo.class, locale);
            } catch (Exception e) {
                log.error("getNotQualifiedSumExportSheet", e);
            }
            notQualifiedSumExportMap.put("title", notQualifiedSumExportParams);
            notQualifiedSumExportMap.put("entityList", notQualifiedSumColList);
            notQualifiedSumExportMap.put("data", notQualifiedSumResList);
            sheetsList.add(notQualifiedSumExportMap);
        }
    }

五、ExcelUtils

package com.ovopark.check.util;

import cn.afterturn.easypoi.excel.annotation.Excel;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import cn.hutool.core.util.ReflectUtil;
import com.ovopark.check.service.impl.MyExcelExportService;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.context.MessageSource;

/**
 * @author: chenheng
 * @create: 2022-05-25 09:20
 * @description:
 **/
public class ExcelUtils {
  /**
   * 用于国际化
   */
  private static MessageSource messageSource = SpringContextUtils.getBean(MessageSource.class);
  /**
   * 一个excel 创建多个sheet
   * @param list
   * @return
   */
  public static SXSSFWorkbook exportExcel(List<Map<String, Object>> list) {
    SXSSFWorkbook workbook = new SXSSFWorkbook();
    for (Map<String, Object> map : list) {
      MyExcelExportService service = new MyExcelExportService();
      service.createSheetWithList(workbook, (ExportParams) map.get("title"), ExportParams.class,
          (List<ExcelExportEntity>) map.get("entityList"), (Collection<?>) map.get("data"));
    }
    return workbook;
  }

  public static void getExcelExportMap(List<ExcelExportEntity> colList, List<Map<String,Object>> resList,
      List list, Class<?> pojoClass, Locale locale) throws IllegalAccessException {
    Field[] classFields = ReflectUtil.getFields(pojoClass);
    //需要导出的属性list
    List<Field> newFields = new ArrayList<>();
    for (Field field : classFields) {
      Excel excel = field.getAnnotation(Excel.class);
      if (excel != null) {
        ExcelExportEntity entity = new ExcelExportEntity();
        entity.setName(messageSource.getMessage(excel.name(), null, locale));
        entity.setKey(field.getName());
        entity.setOrderNum(Integer.parseInt(excel.orderNum()==null?"0":excel.orderNum()));
        colList.add(entity);
        newFields.add(field);
      }
    }
    //数据体
    for (Object obj : list) {
      Map<String, Object> map = new HashMap<>();
      for (Field field : newFields) {
        // 仅在获取用private修饰属性使用
        field.setAccessible(true);
        map.put(field.getName(), field.get(obj)!=null?field.get(obj):"-");
      }
      resList.add(map);
    }
  }

}

六、MyExcelExportService

package com.ovopark.check.service.impl;

import cn.afterturn.easypoi.excel.annotation.ExcelTarget;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import cn.afterturn.easypoi.excel.export.ExcelExportService;
import cn.afterturn.easypoi.exception.excel.ExcelExportException;
import cn.afterturn.easypoi.exception.excel.enums.ExcelExportEnum;
import cn.afterturn.easypoi.util.PoiPublicUtil;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;

/**
 * @author: chenheng
 * @create: 2022-05-25 09:26
 * @description:
 **/
@Slf4j
public class MyExcelExportService extends ExcelExportService {

  public void createSheetWithList(Workbook workbook, ExportParams entity, Class<?> pojoClass, List<ExcelExportEntity> entityList, Collection<?> dataSet) {
    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug("Excel export start ,class is {}", pojoClass);
      LOGGER.debug("Excel version is {}",
          entity.getType().equals(ExcelType.HSSF) ? "03" : "07");
    }
    if (workbook == null || entity == null || pojoClass == null || dataSet == null) {
      throw new ExcelExportException(ExcelExportEnum.PARAMETER_ERROR);
    }
    try {
      List<ExcelExportEntity> excelParams = entityList;
      // 得到所有字段
      Field[] fileds = PoiPublicUtil.getClassFields(pojoClass);
      ExcelTarget etarget = pojoClass.getAnnotation(ExcelTarget.class);
      String targetId = etarget == null ? null : etarget.value();
      getAllExcelField(entity.getExclusions(), targetId, fileds, excelParams, pojoClass,
          null, null);
      //获取所有参数后,后面的逻辑判断就一致了
      createSheetForMap(workbook, entity, excelParams, dataSet);
    } catch (Exception e) {
      LOGGER.error(e.getMessage(), e);
      throw new ExcelExportException(ExcelExportEnum.EXPORT_ERROR, e.getCause());
    }
  }
}

参考:

Easypoi官网

EasyPOI实现多sheet和列数的动态生成

到此这篇关于使用EasyPoi实现多Sheet页导出的示例代码的文章就介绍到这了,更多相关EasyPoi多Sheet页导出内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Java SpringBoot自动装配原理详解及源码注释

    Java SpringBoot自动装配原理详解及源码注释

    SpringBoot的自动装配是拆箱即用的基础,也是微服务化的前提。其实它并不那么神秘,我在这之前已经写过最基本的实现了,大家可以参考这篇文章,来看看它是怎么样实现的,我们透过源代码来把握自动装配的来龙去脉
    2021-10-10
  • spring 参数校验Validation示例详解

    spring 参数校验Validation示例详解

    Spring提供了Validation工具类来实现对客户端传来的请求参数的有效校验,本文给大家介绍spring 参数校验Validation示例详解,感兴趣的朋友一起看看吧
    2024-12-12
  • springboot+thymeleaf打包成jar后找不到静态资源的坑及解决

    springboot+thymeleaf打包成jar后找不到静态资源的坑及解决

    这篇文章主要介绍了springboot+thymeleaf打包成jar后找不到静态资源的坑及解决,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-11-11
  • java原生序列化和Kryo序列化性能实例对比分析

    java原生序列化和Kryo序列化性能实例对比分析

    这篇文章主要介绍了java原生序列化和Kryo序列化性能实例对比分析,涉及Java和kryo序列化和反序列化相关实例,小编觉得很不错,这里分享给大家,希望给大家一个参考。
    2017-10-10
  • Java实现从jar包中读取指定文件的方法

    Java实现从jar包中读取指定文件的方法

    这篇文章主要介绍了Java实现从jar包中读取指定文件的方法,涉及java针对jar文件的读取及查找相关操作技巧,需要的朋友可以参考下
    2017-08-08
  • springboot 使用zookeeper实现分布式队列的基本步骤

    springboot 使用zookeeper实现分布式队列的基本步骤

    这篇文章主要介绍了springboot 使用zookeeper实现分布式队列,通过ZooKeeper的协调和同步机制,多个应用程序可以共享一个队列,并按照先进先出的顺序处理队列中的消息,需要的朋友可以参考下
    2023-08-08
  • Spring中初始化泛型类的方法实例

    Spring中初始化泛型类的方法实例

    这篇文章主要给大家介绍了Spring中如何初始化泛型类,文中给出详细的介绍和方法实例,对大家的理解和学习具有一定的参考借鉴价值,有需要的朋友可以参考学习,下面来一起看看吧。
    2017-01-01
  • MyBatis-Plus 动态表名SQL解析器的实现

    MyBatis-Plus 动态表名SQL解析器的实现

    这篇文章主要介绍了MyBatis-Plus 动态表名SQL解析器的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-08-08
  • Spring boot如何通过@Scheduled实现定时任务及多线程配置

    Spring boot如何通过@Scheduled实现定时任务及多线程配置

    这篇文章主要介绍了Spring boot如何通过@Scheduled实现定时任务及多线程配置,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-12-12
  • 老生常谈 Java中的继承(必看)

    老生常谈 Java中的继承(必看)

    下面小编就为大家带来一篇老生常谈 Java中的继承(必看)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-07-07

最新评论