EasyExcel工具类,一键实现表格导入导出,有无对应实体类均可
Java解析、生成Excel比较有名的框架有Apache poi、jxl。但他们都存在一个严重的问题就是非常的耗内存,poi有一套SAX模式的API可以一定程度的解决一些内存溢出的问题,但POI还是有一些缺陷,比如07版Excel解压缩以及解压后存储都是在内存中完成的,内存消耗依然很大。
easyexcel重写了poi对07版Excel的解析,一个3M的excel用POI sax解析依然需要100M左右内存,改用easyexcel可以降低到几M,并且再大的excel也不会出现内存溢出;03版依赖POI的sax模式,在上层做了模型转换的封装,让使用者更加简单方便。
常规POI解析Excel生成的WorkBook对象时,内存占用特别大,很容易造成系统内存溢出,本工具类可以实现Excel写入并下载到浏览器、Excel读取到集合入库,表格列不固定时,也可。
对应maven
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.0.5</version>
</dependency>
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Component
public class EasyExcelUtil<T> {
private List<Map<Integer, String>> dataList = new ArrayList<>();
private List<T> dataEntityList = new ArrayList<>();
/** 根据文件路径读取表格文件
* @param filePath 文件路径
* @param headRowNumber 读取行数 0代表从第一行开始读取
* @return List<Map<Integer, String>>
*/
public List<Map<Integer, String>> excelReadFilePath(String filePath, Integer headRowNumber) {
ExcelDataListener listener = new ExcelDataListener();
EasyExcel.read(filePath).sheet().registerReadListener(listener).headRowNumber(headRowNumber).doRead();
return dataList;
}
/**
* 根据文件对象读取表格文件
* @param file 文件对象
* @param headRowNumber 读取行数 0代表从第一行开始读取
* @return List<Map<Integer, String>>
*/
public List<Map<Integer, String>> excelReadFile(File file, Integer headRowNumber) {
ExcelDataListener listener = new ExcelDataListener();
EasyExcel.read(file).sheet().registerReadListener(listener).headRowNumber(headRowNumber).doRead();
return dataList;
}
/**
* 根据文件路径读取表格文件,实体类映射
* 实体类需要使用注解 @ExcelProperty("对应表格列名")
* @ExcelIgnore 忽略字段
* @param filePath 文件路径
* @param headRowNumber 读取行数 0代表从第一行开始读取
* @param t 对应实体类
* @return List<T>
*/
public List<T> excelReadFilePathByEntity(String filePath, Integer headRowNumber, Class<T> t) {
EasyExcel.read(filePath, t, new ExcelDataEntityListener()).sheet().headRowNumber(headRowNumber).doRead();
return dataEntityList;
}
/**
*
* @param file 文件对象
* @param headRowNumber 读取行数 0代表从第一行开始读取
* @param t 对应实体类
* @return List<T>
*/
public List<T> excelReadFileByEntity(File file, Integer headRowNumber, T t) {
EasyExcel.read(file, (Class) t, new ExcelDataEntityListener()).sheet().headRowNumber(headRowNumber).doRead();
return dataEntityList;
}
/**
* 监听每一行数据
*/
class ExcelDataEntityListener extends AnalysisEventListener<T> {
@Override
public void invoke(T t, AnalysisContext analysisContext) {
dataEntityList.add(t);
}
@Override
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
dataEntityList.forEach(System.out::println);
}
}
/**
* 监听数据
*/
class ExcelDataListener extends AnalysisEventListener<Map<Integer, String>> {
@Override
public void invoke(Map<Integer, String> rowData, AnalysisContext analysisContext) {
//处理读取的每一行数据,rowData为包含一行Excel数据的map集合
dataList.add(rowData);
}
@Override
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
/*dataList.forEach(map->map.forEach((index,value)->{
System.out.println(index+"--->"+value);//数据打印
}));*/
}
}
/**
* 写入数据到Excel表格,并下载到浏览器
* 入参第一个List为行,0代表第一行,第二个List每一列数据
* 需保证标题列与数列对应,防止数错行
* @param response 响应流
* @param fileName 下载到浏览器的文件名
* @param sheetName sheet页名
* @param header 标题行
* @param data 每一行数据
* @throws IOException
*/
public void writeFileToBrowser(HttpServletResponse response, String fileName, String sheetName, List<List<String>> header, List<List<String>> data) throws IOException {
response.setHeader("Content-Transfer-Encoding", "binary'");
response.setHeader("'Cache-Control", "must-revalidate,post-check=0,pre-check=0");
response.setHeader("Pragma", "public");
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset-UTF-8");
fileName = URLEncoder.encode(fileName, "UTF-8");//解决中文乱码
String header_body = "inline; filename=" + fileName + "; filename*=utf-8" + fileName;
response.setHeader("Content-Disposition", header_body);
EasyExcel.write(response.getOutputStream())
.head(header)
.autoCloseStream(Boolean.FALSE)
.sheet(sheetName)
.doWrite(data);
}
/**
* 写入数据到Excel表格,并下载到浏览器
* 需有对应实体类
*
* @param response 响应流
* @param fileName 下载到浏览器的文件名
* @param sheetName sheet页名
* @param header 标题行对应实体类
* @param data 每一行数据 实体类集合
* @throws IOException
*/
public void writeFileToBrowserByEntity(HttpServletResponse response, String fileName, String sheetName, Class<T> header, List<T> data) throws IOException {
response.setHeader("Content-Transfer-Encoding", "binary'");
response.setHeader("'Cache-Control", "must-revalidate,post-check=0,pre-check=0");
response.setHeader("Pragma", "public");
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset-UTF-8");
fileName = URLEncoder.encode(fileName, "UTF-8");//解决中文乱码
String header_body = "inline; filename=" + fileName + "; filename*=utf-8" + fileName;
response.setHeader("Content-Disposition", header_body);
EasyExcel.write(response.getOutputStream(),header)
.head((Class) header)
.autoCloseStream(Boolean.FALSE)
.sheet(sheetName)
.doWrite(data);
}
}
写操作,有实体类映射时,需加注解@ExcelProperty(“对应表格列名”),不需要导出的列用注解@ExcelIgnore忽略,对于没有固定列,数据列不确定需转化为List ,第一个list为行,第二个list为列,标题行中,每一个列为一个List
,需保证标题列与数据列顺序一致,避免标题与数据错乱,数据库查询的数据可用List<LinkHashMap<String,String>>接收,确保数据顺序可控,在转为List<List>。
读取示例
1.无实体类映射读取
@Autowired
private EasyExcelUtil easyExcelUtil;
/**
* 无实体类读取Excel
* @return
*/
@GetMapping("easyExcelRead1")
public List<Map<Integer, String>> easyExcelRead1(){
List<Map<Integer, String>> list = easyExcelUtil.excelReadFilePath("C:\\Users\\LJW\\Desktop\\11.xlsx", 1);
list.forEach(System.out::println);
return list;
}
运行结果
2.有实体类映射读取
password不读取,用注解@ExcelIgnore标识
import com.alibaba.excel.annotation.ExcelIgnore;
import com.alibaba.excel.annotation.ExcelProperty;
public class UserInfo {
@ExcelProperty("姓名")
private String name;
@ExcelProperty("性别")
private String sex;
@ExcelProperty("身高")
private String height;
@ExcelProperty("年龄")
private String age;
@ExcelProperty("班级")
private String classes;
@ExcelIgnore
private String password;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getHeight() {
return height;
}
public void setHeight(String height) {
this.height = height;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getClasses() {
return classes;
}
public void setClasses(String classes) {
this.classes = classes;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "UserInfo{" +
"name='" + name + '\'' +
", sex='" + sex + '\'' +
", height='" + height + '\'' +
", age='" + age + '\'' +
", classes='" + classes + '\'' +
", password='" + password + '\'' +
'}';
}
}
/**
* 有实体类读取Excel
* @return
*/
@GetMapping("easyExcelRead2")
public List<UserInfo> easyExcelRead2(){
List<UserInfo> list = easyExcelUtil.excelReadFilePathByEntity("C:\\Users\\LJW\\Desktop\\11.xlsx", 1,UserInfo.class);
list.forEach(System.out::println);
return list;
}
3.无实体类映射的写入并下载到浏览器
需要注意标题行List的格式,每一列是一个List
[
[
姓名
]
,
[
性别
]
,
[
身高
]
,
[
年龄
]
,
[
班级
]
]
[[姓名], [性别], [身高], [年龄], [班级]]
[[姓名],[性别],[身高],[年龄],[班级]]
/**
* 无实体类写入Excel
* @return
*/
@GetMapping("easyExcelWrite1")
public void easyExcelWrite1(HttpServletResponse response) throws IOException {
List header =new ArrayList();
List list1 =new ArrayList(Arrays.asList("姓名","性别","身高","年龄","班级"));
list1.forEach(str->{
List list = new ArrayList();
list.add(str);
header.add(list);
});
List data =new ArrayList();
List list2 =new ArrayList(Arrays.asList("张三","男","178cm","17","一班"));
data.add(list2);
easyExcelUtil.writeFileToBrowser(response,"导出文件.xlsx","sheetName",header,data);//不写标题行,header可传null
}
4.有实体类映射的写入并下载到浏览器
/**
* 有实体类读取Excel
* @return
*/
@GetMapping("easyExcelWrite2")
public void easyExcelWrite2(HttpServletResponse response) throws IOException {
UserInfo data = new UserInfo("张三","男","178cm","17","一班");
List list = new ArrayList();
list.add(data);
easyExcelUtil.writeFileToBrowserByEntity(response,"导出文件.xlsx","sheetName",UserInfo.class,list);//不写标题行,header可传null
}