Spring Boot + EasyExcel 导入导出,好用到爆,可以扔掉 POI 了!
IT牧场
共 2200字,需浏览 5分钟
·
2022-02-20 12:46
点击下方“IT牧场”,选择“设为星标”
来源:https://www.jianshu.com/p/4e6aa6342b33
一、EasyExcel
EasyExcel是阿里巴巴开源poi插件之一,主要解决了poi框架使用复杂,sax解析模式不容易操作,数据量大起来容易OOM,解决了POI并发造成的报错。
主要解决方式:通过解压文件的方式加载,一行一行的加载,并且抛弃样式字体等不重要的数据,降低内存的占用。
二、常用注解
Spring Boot 基础就不介绍了,推荐下这个实战教程:
https://www.javastack.cn/categories/Spring-Boot/
三、依赖
com.alibaba
easyexcel
2.1.4
javax.servlet
javax.servlet-api
4.0.1
provided
com.alibaba
fastjson
1.2.47
四、监听
/**
* EasyExcel 导入监听
*/
public class ExcelListener extends AnalysisEventListener {
//可以通过实例获取该值
private List
五、接口导入Excel
try {
//获取文件名
String filename = file.getOriginalFilename();
//获取文件流
InputStream inputStream = file.getInputStream();
//实例化实现了AnalysisEventListener接口的类
ExcelListener listener = new ExcelListener();
//传入参数
ExcelReader excelReader = new ExcelReader(inputStream, ExcelTypeEnum.XLS, null, listener);
//读取信息
excelReader.read(new Sheet(1, 0, Test.class));
//获取数据
List list = listener.getDatas();
if (list.size() > 1) {
for (int i = 0; i < list.size(); i++) {
Testobj = (Test) list.get(i);
JSONObject jo = new JSONObject();
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
六、接口导出Excel
HttpServletResponse response, HttpServletRequest request
try {
String filenames = "111111";
String userAgent = request.getHeader("User-Agent");
if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
filenames = URLEncoder.encode(filenames, "UTF-8");
} else {
filenames = new String(filenames.getBytes("UTF-8"), "ISO-8859-1");
}
response.setContentType("application/vnd.ms-exce");
response.setCharacterEncoding("utf-8");
response.addHeader("Content-Disposition", "filename=" + filenames + ".xlsx");
EasyExcel.write(response.getOutputStream(), Test.class).sheet("sheet").doWrite(testList);
} catch (Exception e) {
}
七、本地导入、本地导出
List testList = new ArrayList<>();
try {
String strUrl = "C:\\Users\\Administrator\\Desktop\\json.xlsx";
File multipartFile = new File(strUrl);
InputStream inputStream = new FileInputStream(multipartFile);
//实例化实现了AnalysisEventListener接口的类
ExcelListener listener = new ExcelListener();
//传入参数
ExcelReader excelReader = new ExcelReader(inputStream, ExcelTypeEnum.XLS, null, listener);
//读取信息
excelReader.read(new Sheet(1, 0, Test.class));
//获取数据
List list = listener.getDatas();
if (list.size() > 1) {
for (int i = 0; i < list.size(); i++) {
Testobj = (Test) list.get(i);
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
try {
String strUrl = "C:\\Users\\Administrator\\Desktop\\json"+System.currentTimeMillis()+".xlsx";
EasyExcel.write(strUrl,Test.class).sheet("sheet").doWrite(testList);
} catch (Exception e) {
}
以上就是EasyExcel的基础使用过程,欢迎点赞关注交流。
干货分享
最近将个人学习笔记整理成册,使用PDF分享。关注我,回复如下代码,即可获得百度盘地址,无套路领取!
•001:《Java并发与高并发解决方案》学习笔记;•002:《深入JVM内核——原理、诊断与优化》学习笔记;•003:《Java面试宝典》•004:《Docker开源书》•005:《Kubernetes开源书》•006:《DDD速成(领域驱动设计速成)》•007:全部•008:加技术群讨论
加个关注不迷路
喜欢就点个"在看"呗^_^
评论