1、前言
在没有EasyExcel之前我们经常使用Apache的poi jar包进行excel的读写,配置起来比较麻烦,也比较消耗内存,阿里开源了EasyExcel,配置上简化了,在一定程度上简化了内存溢出问题。
2、引入jar包
<dependency><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>1.1.2-beta5</version>
</dependency>
3、读Excel
EasyExcel支持对实体类中的属性进行注解&#xff0c;方便后续进行读写操作。
//表示第0行&#xff0c;表头是id
&#64;ExcelProperty(value &#61; "id", index &#61; 0)
3.1 Student实体类
public class Student extends BaseRowModel {&#64;ExcelProperty(value &#61; "id", index &#61; 0)private Integer id;&#64;ExcelProperty(value &#61; "姓名",index &#61; 1)private String name;&#64;ExcelProperty(value &#61; "性别", index &#61; 2)private String sex;&#64;ExcelProperty(value &#61; "年级", index &#61; 3)private Integer grade;&#64;ExcelProperty(value &#61; "年龄", index &#61; 4)private Integer score;public Integer getId() {return id;}public void setId(Integer id) {this.id &#61; id;}public String getName() {return name;}public void setName(String name) {this.name &#61; name;}public String getSex() {return sex;}public void setSex(String sex) {this.sex &#61; sex;}public Integer getGrade() {return grade;}public void setGrade(Integer grade) {this.grade &#61; grade;}public Integer getScore() {return score;}public void setScore(Integer score) {this.score &#61; score;}&#64;Overridepublic String toString() {return "Student{" &#43;"id&#61;" &#43; id &#43;", sex&#61;&#39;" &#43; sex &#43; &#39;\&#39;&#39; &#43;", grade&#61;" &#43; grade &#43;", score&#61;" &#43; score &#43;&#39;}&#39;;}
}
3.2 读取Excel
public static void readExcel(String fileName){try {InputStream inputStream &#61; new FileInputStream(fileName);Sheet sheet &#61; new Sheet(1,1,Student.class);List<Object> studentList &#61; EasyExcelFactory.read(inputStream,sheet);List<Student> students &#61; new LinkedList<Student>();for (Object student : studentList){students.add((Student)student);}for (Student student : students){System.out.println(student);}} catch (Exception e) {e.printStackTrace();}}
//结果&#xff1a;
Student{id&#61;1, sex&#61;&#39;男&#39;, grade&#61;1, score&#61;12}
Student{id&#61;2, sex&#61;&#39;女&#39;, grade&#61;2, score&#61;13}
4、写Excel
public static void writeExcel(String fileName,List<Student> students) {OutputStream outputStream &#61; null;try {outputStream &#61; new FileOutputStream(fileName);ExcelWriter writer &#61; new ExcelWriter(outputStream, ExcelTypeEnum.XLSX);Sheet sheet &#61; new Sheet(2, 0, Student.class);writer.write(students, sheet);writer.finish();} catch (Exception e) {e.printStackTrace();} finally {if (outputStream !&#61; null) {try {outputStream.close();} catch (IOException e) {e.printStackTrace();}}}}