1. 简介

  Java解析、生成Excel比较有名的框架有Apache poi、jxl。但他们都存在一个严重的问题就是非常的耗内存,poi有一套SAX模式的API可以一定程度的解决一些内存溢出的问题,但POI还是有一些缺陷,比如07版Excel解压缩以及解压后存储都是在内存中完成的,内存消耗依然很大。easyexcel重写了poi对07版Excel的解析,能够原本一个3M的excel用POI sax依然需要100M左右内存降低到几M,并且再大的excel不会出现内存溢出,03版依赖POI的sax模式,在上层做了模型转换的封装,让使用者更加简单方便。

  64M内存1分钟内读取75M(46W行25列)的Excel:



  更多请参考:https://github.com/alibaba/easyexcel

2. 示例代码

  • 创建工程

  • 修改pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.c3stones</groupId>
<artifactId>spring-boot-easyexcel-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-boot-easyexcel-demo</name>
<description>SpringBoot + Easyexcel Demo</description> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.8.RELEASE</version>
<relativePath />
</parent> <dependencies>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.2.6</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies> </project>
  • 创建实体
import java.util.Date;

import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import com.alibaba.excel.annotation.write.style.ContentRowHeight;
import com.alibaba.excel.annotation.write.style.HeadRowHeight; import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor; /**
* 学生实体
*
* @author CL
*
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@HeadRowHeight(20)
@ColumnWidth(20)
@ContentRowHeight(15)
public class Student { @ExcelProperty(index = 0, value = "学号")
private String sno; @ExcelProperty(index = 1, value = "姓名")
private String name; @ExcelProperty(index = 2, value = "年龄")
private Integer age; @ExcelProperty(index = 3, value = "性别")
private String gender; @ExcelProperty(index = 4, value = "籍贯")
private String nativePlace; @ExcelProperty(index = 5, value = "入学时间")
private Date enrollmentTime; }
  • 创建文件读取类

      该类需要继承抽象类AnalysisEventListener,但是不需要被Spring管理。
import java.util.ArrayList;
import java.util.List; import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.c3stones.entity.Student; import lombok.Getter; /**
* 学生读取类
*
* @author CL
*
*/
public class StudentListener extends AnalysisEventListener<Student> { @Getter
private List<Student> studentList = new ArrayList<Student>(); public StudentListener() {
super();
studentList.clear();
} /**
* 每一条数据解析都会调用
*/
@Override
public void invoke(Student student, AnalysisContext context) {
studentList.add(student);
} /**
* 所有数据解析完成都会调用
*/
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
studentList.forEach(System.out::println);
} }
  • 创建文件导出导入Controller示例
import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile; import com.alibaba.excel.EasyExcel;
import com.c3stones.entity.Student;
import com.c3stones.listener.StudentListener; /**
* 学生Controller
*
* @author CL
*
*/
@RestController
@RequestMapping(value = "student")
public class StudentController { /**
* 导出学生信息
*
* @param response
* @param request
* @throws IOException
* @throws ParseException
*/
@SuppressWarnings("serial")
@RequestMapping(value = "export")
public void exportStudentInfos(HttpServletResponse response, HttpServletRequest request)
throws IOException, ParseException {
// 设置响应类型
response.setContentType("application/vnd.ms-excel");
// 设置字符编码
response.setCharacterEncoding("utf-8");
// 设置响应头信息
response.setHeader("Content-disposition",
"attachment;filename*=utf-8''" + URLEncoder.encode("学生花名册", "UTF-8") + ".xlsx"); List<Student> studentList = new ArrayList<Student>() {
{
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
add(new Student("1001", "张三", 23, "男", "陕西西安", dateFormat.parse("2020-09-01")));
add(new Student("1002", "李四", 22, "女", "陕西渭南", dateFormat.parse("2020-09-01")));
}
}; // 写入文件
EasyExcel.write(response.getOutputStream(), Student.class).sheet("学生信息").doWrite(studentList);
} /**
* 导入学生信息
*
* @param file
* @throws IOException
*/
@RequestMapping(value = "import")
public List<Student> importStudentInfos(MultipartFile file) throws IOException {
StudentListener studentListener = new StudentListener();
EasyExcel.read(file.getInputStream(), Student.class, studentListener).sheet().doRead();
return studentListener.getStudentList();
} }
  • 创建文件读取写入Controller示例
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import com.alibaba.excel.EasyExcel;
import com.c3stones.entity.Student;
import com.c3stones.listener.StudentListener; /**
* 文件Controller
*
* @author CL
*
*/
@RestController
@RequestMapping(value = "file")
public class FileController { /**
* 读取Excel
*
* @return
*/
@RequestMapping(value = "readExcel")
public List<Student> readExcel() {
String fileName = "C:\\Users\\Administrator\\Desktop\\学生花名册.xlsx";
StudentListener studentListener = new StudentListener();
EasyExcel.read(fileName, Student.class, studentListener).sheet().doRead();
return studentListener.getStudentList();
} /**
* 写入Excel
*
* @return
* @throws ParseException
*/
@SuppressWarnings("serial")
@RequestMapping(value = "writeExcel")
public Boolean writeExcel() throws ParseException {
String fileName = "C:\\Users\\Administrator\\Desktop\\学生花名册2.xlsx"; List<Student> studentList = new ArrayList<Student>() {
{
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
add(new Student("2001", "张三2", 23, "男", "陕西西安", dateFormat.parse("2020-09-01")));
add(new Student("2002", "李四2", 22, "女", "陕西渭南", dateFormat.parse("2020-09-01")));
}
}; EasyExcel.write(fileName, Student.class).sheet("学生信息2").doWrite(studentList);
return true;
} }
  • 创建启动类
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; /**
* 启动类
*
* @author CL
*
*/
@SpringBootApplication
public class Application { public static void main(String[] args) {
SpringApplication.run(Application.class, args);
} }
  • 启动项目

3. 测试

  通过Postman依次测试导出、导入、读取和写入:

  • 测试导出



      将导出文件保存到桌面(学生花名册.xlsx)。
  • 测试导入

  • 测试读取

  • 测试写入



      可以看到在代码中配置的文件目录已存在写入成功的文件(学生花名册2.xlsx)。

4. 项目地址

  spring-boot-easyexcel-demo

SpringBoot基于EasyExcel解析Excel实现文件导出导入、读取写入的更多相关文章

  1. SpringBoot基于easyexcel导出和写入Excel

      easyexcel是阿里巴巴旗下开源项目,主要用于Excel文件的导入和导出处理,今天我们利用SpringBoot和easyexcel实战演示如何导出和写入Excel文件. 一.加入我们需要的ea ...

  2. SpringBoot整合Easyexcel操作Excel,闲暇之余,让我们学习更多

    关于封面:晚饭后回自习室的路上 Easyexcel 官方文档 Easyexcel | github 前言 最近也是在写的一个小练习中,需要用到这个.趁着这次就将写个整合的Demo给大家. 希望能够让大 ...

  3. 手动解析Excel获取文件元数据

    工作中有遇到需要获取上传的Excel文件的列明.最大行数.大小等元数据信息.通常做法是通过Apache的POI工具加载文件然后再读取行列进行处理.这种方法很大的弊端就是需要把excel文件加载到内存, ...

  4. SpringBoot整合easyexcel实现Excel的导入与导出

    导出 在一般不管大的或者小的系统中,各家的产品都一样,闲的无聊的时候都喜欢让我们这些程序员导出一些数据出来供他观赏,非说这是必须需求,非做不可,那么我们就只能苦逼的哼哧哼哧的写bug喽. 之前使用PO ...

  5. springboot整合easyexcel实现Excel导入导出

    easyexcel:快速.简单避免OOM的java处理Excel工具 Java解析.生成Excel比较有名的框架有Apache poi.jxl.但他们都存在一个严重的问题就是非常的耗内存,poi有一套 ...

  6. excel poi 文件导出,支持多sheet、多列自动合并。

    参考博客: http://www.oschina.net/code/snippet_565430_15074 增加了多sheet,多列的自动合并. 修改了部分过时方法和导出逻辑. 优化了标题,导出信息 ...

  7. C#_服务器EXCEL模板文件导出

    A-1:EXCEL模板导出 非常简单,将EXCEL模板上传到项目中后,将其浏览URL保存下来(excelUrl),然后: window.location.href="http://local ...

  8. EasyExcel 解析excel

    参考:https://blog.csdn.net/jiangjiandecsd/article/details/81115622 https://blog.csdn.net/jianggujin/ar ...

  9. MYSQL 大文件导出导入

    1.导出sql文件 mysqldump  --column-statistics=0 -uusername -ppassword -hyour server ip --default-characte ...

随机推荐

  1. JavaScript监听页面可见性(焦点)同时改变title的三种方法

    JavaScript监听页面可见性(焦点)同时改变title的三种方法 本文参考了https://developer.mozilla.org/zh-CN/docs/Web/API/Page_Visib ...

  2. 面试必看!靠着这份字节和腾讯的面经,我成功拿下了offer!

    准备 敲定了方向和目标后就开始系统准备,主要分为以下几个方面来准备. 算法题 事先已经看过别人的社招面经知道头条每轮技术面都有算法题,而这一块平时练习的比较少,校招时刷的题也忘记了很多.因此系统复习的 ...

  3. 标准库之time,random,sys,os

    # import time # print(time.time()) # 时间戳 # print(time.mktime(time.localtime())) # 结构化时间转换为时间戳 # prin ...

  4. Java线程的死锁和活锁

    目录 1.概览 2.死锁 2.1.什么是死锁 2.2 死锁举例 2.3 避免死锁 3.活锁 3.1 什么是活锁 3.2 活锁举例 3.3 避免活锁 1.概览 当多线程帮助我们提高应用性能的同时,它同时 ...

  5. C语言讲义——字符串库函数

    字符串库函数<string.h> 求字符串长度(不含结束符'\0'****) strlen(str) 字符串赋值(可能造成数组越界) strcpy(str," 水浒传 " ...

  6. django搭建完毕运行显示hello django

    1.使用pycharm打开工程,进入工程配置解释器路径 2.视图和url 视图:处理我们从业务的地方,可以理解为函数 url:进行路由匹配的地方,先在主工程bookpro中进行匹配,如果匹配ok,那么 ...

  7. HTML的基本术语

    一.HTML含义1.根据W3C定义,HTML全称Hyper Text Markup Language: 超文本标记语言,用于定义文档的内容结构,该语言书写的代码通常会被浏览器解析执行.二.css含义1 ...

  8. CentOS升级参考

    CentOS生产系统升级策略: 1)升级前评估 a)确认kernel或包bug. b)用评估工具 c) 测试验证 2)确认升级内容 a)单独升级kernel b)单独升级包 c)都升级 4)确认升级方 ...

  9. python - os.sep用法

    python是跨平台的.在Windows上,文件的路径分隔符是'\',在Linux上是'/'.为了让代码在不同的平台上都能运行,那么路径应该写'\'还是'/'呢?使用os.sep的话,就不用考虑这个了 ...

  10. mininet + opendaylight环境配置

    环境配置 ubuntu18.04 镜像 mininet2.2.2 apt-get install mininet 但这种安装只是TLS版本的mininet,与最新版本在功能上有所差距. 控制器(ope ...