EasyExcel是一个基于Java的简单、省内存的读写Excel的开源项目。
一、导入maven坐标
Lombok可选,不导入的话需要手动写getter、setter、tostring
<!-- easyexcel-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.1.1</version>
</dependency>
<!--xls-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version> 1.18.16</version>
</dependency>
二、编写Excel表格实体类
这里@Data就是Lombok的注解,不用自己写getter、setter、tostring
@Data
public class StudentExcel {
//设置excel表头名称
@ExcelProperty(value = "学号")
private Integer sno;
@ExcelProperty(value = "姓名")
private String sname;
@ExcelProperty(value = "性别")
private Integer ssex;
}
三、写操作
public class TestEasyExcel {
public static void main(String[] args) {
String filename = "D:\\student.xlsx";
testWriteExcel(filename);
}
public static void testWriteExcel(String filename){
//实现excel写的操作
//调用easyexcel里面的方法实现写操作
//write方法两个参数:第一个参数文件路径名称,第二个参数实体类class getData()是要写的入的实体类List
EasyExcel.write(filename,StudentExcel.class).sheet("学生列表").doWrite(getData());
}
//创建方法返回list集合
private static List<StudentExcel> getData() {
List<StudentExcel> list = new ArrayList<>();
String[] name={"tom","jack","tony","小明","小红"};
for (int i = 0; i < 5; i++) {
StudentExcel data = new StudentExcel();
data.setSno(i);
data.setSname(name[i]);
data.setSsex(1);
list.add(data);
}
return list;
}
}
四、读操作
1.编写监听器
public class ExcelListener extends AnalysisEventListener<StudentExcel> {
//一行一行读取excel内容
@Override
public void invoke(StudentExcel data, AnalysisContext analysisContext) {
System.out.println("excel数据:"+data);
}
//读取表头内容
@Override
public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
System.out.println("表头:"+headMap);
}
//读取完成之后
@Override
public void doAfterAllAnalysed(AnalysisContext analysisContext) { }
}
2.读取数据
public static void main(String[] args) {
String filename = "D:\\student.xlsx";
testReadExcel(filename);
}
public static void testReadExcel(String filename){
//实现excel读操作
EasyExcel.read(filename, StudentExcel.class,new ExcelListener()).sheet().doRead();
}
帮助到您请点赞关注收藏谢谢!!
来源:oschina
链接:https://my.oschina.net/u/4806815/blog/4733814