easypoi导出excel

需求

工作过程中通常会遇到需要导出excel的需求,比如导出用户信息、订单信息等。
导出数据量较小的情况下,可以直接使用easypoi提供的工具类,将数据写入到excel中。

引入依赖


<dependency>
    <groupId>cn.afterturn</groupId>
    <artifactId>easypoi-base</artifactId>
    <version>4.1.2</version>
    <scope>compile</scope>
</dependency>

创建导出时用到的实体类

import lombok.Data;
import cn.afterturn.easypoi.excel.annotation.Excel;

@Data
public class User {
    @Excel(name = "姓名")
    private String name;
    @Excel(name = "年龄")
    private Integer age;
    @Excel(name = "性别")
    private String sex;
    @Excel(name = "电话")
    private String phone;
    @Excel(name = "邮箱")
    private String email;
    @Excel(name = "地址")
    private String address;

}

调用easypoi导出excel

导出单个sheet页示例

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/export")
public class ExportController {
    /**
     * 导出用户信息
     */
    @GetMapping("/userExport")
    public void userExport(HttpServletResponse response) {
        ExportParams params = new ExportParams("用户信息", "sheet1", ExcelType.XSSF);
        List<User> userList = new ArrayList<>();
        // 假设有10000条用户数据
        for (int i = 0; i < 10000; i++) {
            User user = new User();
            user.setName("张三" + i);
            user.setAge(20 + i);
            user.setSex("男");
            user.setPhone("13811111111");
            user.setEmail("zhang@163.com");
            user.setAddress("北京市");
            userList.add(user);
        }
        // 导出到excel
        Workbook workbook = ExcelExportUtil.exportExcel(params, User.class, userList);
        // 将工作表写入响应流
        response.setHeader("Content-disposition", "attachment;filename="+ URLEncoder.encode("用户信息.xlsx","UTF-8"));// filename是下载的xls的名,建议最好用英文
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");// 设置类型
        response.setHeader("Pragma", "No-cache");// 设置头
        response.setHeader("Cache-Control", "no-cache");// 设置头
        response.setDateHeader("Expires", 0);// 设置日期头
        OutputStream out = response.getOutputStream();
        workbook.write(out);
        out.flush();
        out.close();
    }
}

导出多个sheet页示例

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/export")
public class ExportController {
    /**
     * 导出用户信息
     */
    @GetMapping("/userExport")
    public void userExport(HttpServletResponse response) {
        ExportParams params = new ExportParams("用户信息", "sheet1", ExcelType.XSSF);
        List<User> userList = new ArrayList<>();
        // 假设有10000条用户数据
        for (int i = 0; i < 10000; i++) {
            User user = new User();
            user.setName("张三" + i);
            user.setAge(20 + i);
            user.setSex("男");
            user.setPhone("13811111111");
            user.setEmail("zhang@163.com");
            user.setAddress("北京市");
            userList.add(user);
        }
        // sheet页列表,每个Map对象代表一个sheet页
        List<Map<String, Object>> sheetsList = new ArrayList<>();
        sheetsList.add(
                new HashMap<String, Object>(){{
                    put("title", params);
                    put("entity", User.class);
                    put("data", userList);
                }}
        );
        // 下面按照同样的方式添加多个sheet页
        
        // 导出到excel,这里导出时,每个sheet页都必须把导出类型设置为 XSSF(或与下面一行代码中参数一致),否则会报错
        Workbook workbook = ExcelExportUtil.exportExcel(sheetsList, ExcelType.XSSF);
        // 将工作表写入响应流
        response.setHeader("Content-disposition", "attachment;filename="+ URLEncoder.encode("用户信息.xlsx","UTF-8"));// filename是下载的xls的名,建议最好用英文
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");// 设置类型
        response.setHeader("Pragma", "No-cache");// 设置头
        response.setHeader("Cache-Control", "no-cache");// 设置头
        response.setDateHeader("Expires", 0);// 设置日期头
        OutputStream out = response.getOutputStream();
        workbook.write(out);
        out.flush();
        out.close();
    }
}

导出单个sheet页调用
cn.afterturn.easypoi.excel.ExcelExportUtil
中的 exportExcel 方法,传入参数为:

  • ExportParams 参数对象,用于设置导出文件的名称、sheet页名称、文件类型等信息。
  • Class 实体类,用于指定导出的数据类型。
  • List 数据列表,用于指定导出的数据。
import cn.afterturn.easypoi.excel.entity.ExportParams;

import java.util.Collection;

public class ExcelExportUtil {
    /**
     * @param entity    表格标题属性
     * @param pojoClass Excel对象Class
     * @param dataSet   Excel对象数据List
     */
    public static Workbook exportExcel(ExportParams entity, Class<?> pojoClass,
                                       Collection<?> dataSet) {
        Workbook workbook = getWorkbook(entity.getType(), dataSet.size());
        new ExcelExportService().createSheet(workbook, entity, pojoClass, dataSet);
        return workbook;
    }
}

导出多个sheet页调用
cn.afterturn.easypoi.excel.ExcelExportUtil
中的 exportExcel 方法,传入参数为:

  • List<Map<String, Object>> 参数对象,用于设置多个sheet页的导出信息。
  • ExcelType 导出类型,用于指定文件类型。
public class ExcelExportUtil {
    /**
     * 根据Map创建对应的Excel(一个excel 创建多个sheet)
     *
     * @param list 多个Map key title 对应表格Title key entity 对应表格对应实体 key data
     *             Collection 数据
     * @return
     */
    public static Workbook exportExcel(List<Map<String, Object>> list, ExcelType type) {
        Workbook workbook = getWorkbook(type, 0);
        for (Map<String, Object> map : list) {
            ExcelExportService service = new ExcelExportService();
            service.createSheet(workbook, (ExportParams) map.get("title"),
                    (Class<?>) map.get("entity"), (Collection<?>) map.get("data"));
        }
        return workbook;
    }
}

导出参数
cn.afterturn.easypoi.excel.entity.ExportParams
中常用的属性有:

  • title: 表格标题
  • sheetName: 工作表名称(sheet页名称)
  • type: 导出类型

easypoi提供了类型枚举类 cn.afterturn.easypoi.excel.entity.enmus.ExcelType
包括:HSSF, XSSF。HSSF对应 .xls格式,XSSF对应.xlsx格式

表格标题示例,以下表格标题为 ‘用户信息’,如下:

用户信息
姓名年龄性别电话邮箱地址
张三2013811111111zhang@163.com北京市

生成工作表方法,在传入的数据量超过十万时,使用SXSSFWorkbook,可防止内存溢出。

public class ExcelExportUtil {
    public static       int    USE_SXSSF_LIMIT = 100000;
    private static Workbook getWorkbook(ExcelType type, int size) {
        if (ExcelType.HSSF.equals(type)) {
            return new HSSFWorkbook();
        } else if (size < USE_SXSSF_LIMIT) {
            return new XSSFWorkbook();
        } else {
            return new SXSSFWorkbook();
        }
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

忆昔年.

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

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

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

打赏作者

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

抵扣说明:

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

余额充值