需求
工作过程中通常会遇到需要导出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格式
表格标题示例,以下表格标题为 ‘用户信息’,如下:
用户信息 | |||||
---|---|---|---|---|---|
姓名 | 年龄 | 性别 | 电话 | 邮箱 | 地址 |
张三 | 20 | 男 | 13811111111 | zhang@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();
}
}
}