一、简介
作者对easyExcel的描述:Java解析、生成Excel比较有名的框架有Apache poi、jxl。但他们都存在一个严重的问题就是非常的耗内存,poi有一套SAX模式的API可以一定程度的解决一些内存溢出的问题,但POI还是有一些缺陷,比如07版Excel解压缩以及解压后存储都是在内存中完成的,内存消耗依然很大。easyexcel重写了poi对07版Excel的解析,能够原本一个3M的excel用POI sax依然需要100M左右内存降低到KB级别,并且再大的excel不会出现内存溢出,03版依赖POI的sax模式。在上层做了模型转换的封装,让使用者更加简单方便。
二、快速上手
使用步骤:
- 添加依赖
1 <!--Excel包--> 2 <!-- https://mvnrepository.com/artifact/com.alibaba/easyexcel --> 3 <dependency> 4 <groupId>com.alibaba</groupId> 5 <artifactId>easyexcel</artifactId> 6 <version>1.1.2-beta5</version> 7 </dependency>
- 七行代码就可以实现简单的Excel导出
@Test public void ExportTest() throws IOException { //指定文件输出位置 OutputStream outputStream =new FileOutputStream("H:/excel/file/myexcel3.xlsx"); ExcelWriter excelWriter =EasyExcelFactory.getWriter(outputStream); //将要输出的内容填充到Sheet里 Sheet sheet =new Sheet(1,0,ExcelModel.class ); //设置sheet表名 sheet.setSheetName("my_three_excel"); /** * 写数据到Write上下文中 * 第一个参数:要写入的内容 * 第二个参数:要写入的sheet目标 */ excelWriter.write(createModelList2(),sheet); excelWriter.finish(); outputStream.close(); }
-
上面使用到的ExcelModel.class需要自己定义,首先需要继承BaseRowModel,其次,通过
@ExcelProperty
注解来指定每个字段的列名称,以及下标位置;@Data public class ExcelMode extends BaseRowModel { @ExcelProperty(value = "姓名" ,index = 0) private String userName; @ExcelProperty(value = "年龄" ,index = 1) private String age; @ExcelProperty(value = "住址" ,index = 2) private String address; }
填充的数据:
private List<ExcelMode> createModelList (){ List<ExcelMode> list = new ArrayList<>(); for(int i=0; i<20;i++){ ExcelMode excelMode = new ExcelMode(); excelMode.setUserName("哒哒"+i); excelMode.setAge("22"); excelMode.setAddress("广西"); list.add(excelMode); } return list; }
-
设置二级表头
@Data public class ExcelModel2 extends BaseRowModel { @ExcelProperty(value = {"name","name"},index = 0) private String name; @ExcelProperty(value ={"age","age"},index = 1) private String age; @ExcelProperty(value={"cash_value","高"},index = 2) private String cashvalue_high ; @ExcelProperty(value={"cash_value","中"},index = 3) private String cashvalue_during ; @ExcelProperty(value={"cash_value","低"},index = 4) private String cashvalue_low ; }
@Data public class ExcelModel2 extends BaseRowModel { @ExcelProperty(value = {"name","name"},index = 0) private String name; @ExcelProperty(value ={"age","age"},index = 1) private String age; @ExcelProperty(value={"cash_value","高"},index = 2) private String cashvalue_high ; @ExcelProperty(value={"cash_value","中"},index = 3) private String cashvalue_during ; @ExcelProperty(value={"cash_value","低"},index = 4) private String cashvalue_low ; }
结果:
- 七行代码就可以实现简单的Excel导出