Java解析、生成Excel比较有名的框架有Apache poi、jxl。但他们都存在一个严重的问题就是很是的耗内存,poi有一套SAX模式的API能够必定程度的解决一些内存溢出的问题,但POI仍是有一些缺陷,好比07版Excel解压缩以及解压后存储都是在内存中完成的,内存消耗依然很大。java
easyexcel重写了poi对07版Excel的解析,可以本来一个3M的excel用POI sax依然须要100M左右内存下降到KB级别,而且再大的excel不会出现内存溢出,03版依赖POI的sax模式。在上层作了模型转换的封装,让使用者更加简单方便
详细使用及介绍请参考官网git
建立springboot工程,而后引入相关依赖包以下:github
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>
工程结构以下图:
web
springboot工程建立好以后,引入easyExcel依赖包便可,使用前最好咨询下最新版,或者到mvn仓库搜索先easyexcel的最新版,本文使用的是以下版本spring
<dependency> <groupId>com.alibaba</groupId> <artifactId>easyexcel</artifactId> <version>1.1.2-beta5</version> </dependency>
而后建立User实体类并继承BaseRowModel ,而后在对应字段上添加注解数据库
@Data @Builder public class User extends BaseRowModel { @ExcelProperty(value = "姓名",index = 0) private String name; @ExcelProperty(value = "密码",index = 1) private String password; @ExcelProperty(value = "年龄",index = 2) private Integer age; }
注:@Data,@Builder注解是引入的lombok的注解,省略了get/set方法。@Builder是后边方便批量建立实体类所用的。
@ExcelProperty注解是引入的easyExcel依赖包中的,上面字段注解的意思value是表头名称,index是第几列,能够参考以下图:
springboot
以后建立UserController类并建立返回list集合的方法,用于测试输出Excel表中框架
public List<User> getAllUser(){ List<User> userList = new ArrayList<>(); for (int i=0;i<100;i++){ User user = User.builder().name("张三"+ i).password("1234").age(i).build(); userList.add(user); } return userList; }
上面for循环目的是用了批量建立list集合,你能够本身一个个的建立spring-boot
下面进行测试,工具
public class EasyexceldemoApplicationTests { //注入controller类用来调用返回list集合的方法 @Autowired private UserController userController; @Test public void contextLoads(){ // 文件输出位置 OutputStream out = null; try { out = new FileOutputStream("C:\\Users\\smfx1314\\Desktop\\bbb\\test.xlsx"); ExcelWriter writer = EasyExcelFactory.getWriter(out); // 写仅有一个 Sheet 的 Excel 文件, 此场景较为通用 Sheet sheet1 = new Sheet(1, 0, User.class); // 第一个 sheet 名称 sheet1.setSheetName("第一个sheet"); // 写数据到 Writer 上下文中 // 入参1: 数据库查询的数据list集合 // 入参2: 要写入的目标 sheet writer.write(userController.getAllUser(), sheet1); // 将上下文中的最终 outputStream 写入到指定文件中 writer.finish(); } catch (FileNotFoundException e) { e.printStackTrace(); }finally { try { // 关闭流 out.close(); } catch (IOException e) { e.printStackTrace(); } } } }
注:文件输出位置要自定义好,包括xxx.xlsx文档名称,意思数据输出就在这个文档了。
sheet1.setSheetName("第一个sheet")用了设置文档名称,看下图:
测试成功,而后看看你的xxx.xlsx文档里面是否有内容输出
源码参考