一、Easy-POI简介
Easypoi功能如同名字easy,主打的功能就是容易,让一个没见接触过poi的人员就可以方便的写出Excel导出,Excel模板导出,Excel导入,Word模板导出,通过简单的注解和模板。
地址:https://opensource.afterturn.cn/
二、Maven依赖
<!--excel操作-->
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-spring-boot-starter</artifactId>
<version>4.1.0</version>
</dependency>
三、导入导出Excel
- 导入工具类
package com.xtsz.spring.producer.common;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
@Slf4j
public class ExcelUtils {
/**
* 导出实体类型数据带标题与工作表
* @param list 数据
* @param title 标题
* @param sheetName sheet名称
* @param pojoClass pojo类型
* @param fileName 文件名称
* @param isCreateHeader 是否创建表头
* @param response http响应对象
*/
public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass,
String fileName, boolean isCreateHeader, HttpServletResponse response){
ExportParams exportParams = new ExportParams(title, sheetName);
exportParams.setCreateHeadRows(isCreateHeader);
defaultExport(list, pojoClass, fileName, response, exportParams);
}
/**
*
* @param list 数据
* @param title 标题
* @param sheetName sheet名称
* @param pojoClass pojo类型
* @param fileName 文件名称
* @param response http响应对象
*/
public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass,String fileName,
HttpServletResponse response){
defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName));
}
/**
* 导出Map类型数据
* @param list 数据
* @param fileName 文件名称
* @param response http响应对象
*/
public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response){
defaultExport(list, fileName, response);
}
/**
* 导出实体类型数据
* @param list 数据
* @param pojoClass pojo类型
* @param fileName 文件名称
* @param response http响应对象
* @param exportParams 导出参数
*/
private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName,
HttpServletResponse response, ExportParams exportParams) {
Workbook workbook = ExcelExportUtil.exportExcel(exportParams,pojoClass,list);
if (workbook != null); downLoadExcel(fileName, response, workbook);
}
/**
* 下载Excel,导出文件使用
* @param fileName 文件名称
* @param response http响应对象
* @param workbook excel数据
*/
private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
try {
response.setCharacterEncoding("UTF-8");
response.setHeader("content-Type", "application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
workbook.write(response.getOutputStream());
} catch (IOException e) {
log.info(e.getMessage());
}
}
/**
* 默认导出
* @param list 数据
* @param fileName 文件名
* @param response http响应对象
*/
private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) {
Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
if (workbook != null);
downLoadExcel(fileName, response, workbook);
}
/**
* excel 导入
*
* @param filePath excel文件路径
* @param titleRows 标题行
* @param headerRows 表头行
* @param pojoClass pojo类型
* @param <T>
* @return
*/
public static <T> List<T> importExcel(String filePath,Integer titleRows,Integer headerRows, Class<T> pojoClass){
if (StringUtils.isBlank(filePath)){
return null;
}
ImportParams params = new ImportParams();
params.setTitleRows(titleRows);
params.setHeadRows(headerRows);
List<T> list = null;
try {
list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
}catch (NoSuchElementException e){
log.info(e.getMessage());
} catch (Exception e) {
e.printStackTrace();
log.info(e.getMessage());
} return list;
}
/**
* MultipartFile 类型导入
* @param file excel文件
* @param titleRows 表格标题行数,默认0
* @param headerRows 表头行数,默认1,注意:不是列数
* @param pojoClass pojo类型
* @param <T>
* @return
*/
public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass){
if (file == null){ return null;
}
ImportParams params = new ImportParams();
params.setTitleRows(titleRows);
params.setHeadRows(headerRows);
// 是否需要校验,保存Excel必须设置
params.setNeedVerify(true);
// 指定文件保存
params.setNeedSave(true);
// 默认文件保存路径: /excel/upload
// 图片路径,请在实体类使用注解指定
// 如果指定/为所在项目的盘符,如果在上传到resources目录,请获取该目录的绝对路径
params.setSaveUrl("./static");
List<T> list = null;
try {
list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
}catch (NoSuchElementException e){
log.info(e.getMessage());
} catch (Exception e) {
log.info(e.getMessage());
}
return list;
}
}
- 实体类
@Data
public class User {
/**
* 姓名
*/
@Excel(name = "姓名", orderNum = "0", width = 15)
private String name;
/**
* 登录用户名
*/
@Excel(name = "用户名", orderNum = "1", width = 15)
private String username;
@Excel(name = "手机号码", orderNum = "2", width = 15)
private String phoneNumber;
/**
* 人脸图片
* 图片保存路径:savePath
*/
@Excel(name = "人脸图片", orderNum = "3", width = 15, height = 30, type = 2,savePath = "/static")
private String imageUrl;
}
注意:图片路径,使用注解添加。
- 控制器类
@RestController
@RequestMapping("/excel")
@Slf4j
public class ExcelController {
/**
* 导出
*
* @param response
*/
@GetMapping(value = "/export")
public void exportExcel(HttpServletResponse response) {
long start = System.currentTimeMillis();
List<User> users = new ArrayList<>();
for (int i = 0; i < 5; i++) {
User user = new User();
user.setName("张三" + i);
user.setUsername("张三" + i);
user.setPhoneNumber("18888888888");
user.setImageUrl("/001.jpg");
users.add(user);
}
log.debug("导出excel所花时间:" + (System.currentTimeMillis() - start));
ExcelUtils.exportExcel(users, "员工信息表", "员工信息", User.class, "员工信息.xls", response);
}
/**
* 导入
*
* @param file
*/
@PostMapping(value = "/import")
public String importExcel(@RequestParam("file") MultipartFile file) {
long start = System.currentTimeMillis();
List<User> users = ExcelUtils.importExcel(file,1,1, User.class);
log.info(users.toString());
log.info("导入excel所花时间:" + (System.currentTimeMillis() - start));
return "导入成功";
}
}
- 测试
- 导出测试
导出地址:http://localhost:8089/excel/export
- 导入测试
地址:http://localhost:8089/excel/import
四、常见问题:
- lastRow < firstRow || lastCol < firstCol
解决:
在要导出的实体类字段上添加注解。
@Excel(name = "登录账号", orderNum = "0",width = 15)
- the request was rejected because its size (44711128) exceeds the configured maximum (10485760)
解决办法:
在application.properties中增加配置
# 设置文件大小
# 设置文件大小(KB MB GB TB) 或-1为没有限制
spring.servlet.multipart.maxFileSize=100MB
spring.servlet.multipart.maxRequestSize=100MB