MAVEN
xml
<!-- https://mvnrepository.com/artifact/com.alibaba/easyexcel -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.0.5</version>
</dependency>
代码
java
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
// 定义你的数据类,用于映射Excel中的字段
public class YourDataClass {
// 定义字段,与Excel列名对应
@ExcelProperty(index = 1)
private String field1;
@ExcelProperty(index = 2)
private String field2;
// getters and setters
public String getField1() {
return field1;
}
public void setField1(String field1) {
this.field1 = field1;
}
public String getField2() {
return field2;
}
public void setField2(String field2) {
this.field2 = field2;
}
@Override
public String toString() {
return "YourDataClass{" +
"field1='" + field1 + '\'' +
", field2='" + field2 + '\'' +
'}';
}
}
// 自定义监听器,用于处理读取到的数据
class YourDataListener extends AnalysisEventListener<YourDataClass> {
@Override
public void invoke(YourDataClass data, AnalysisContext context) {
System.out.println(data);
// 处理每条数据,例如保存到数据库或其他操作
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
// 所有数据处理完毕后的操作
System.out.println("doAfterAllAnalysed");
}
}
// 读取Excel文件
class YourExcelReader {
public void readExcel(String fileName) {
// 读取第一个sheet
EasyExcel.read(fileName, YourDataClass.class, new YourDataListener())
.sheet()
.doRead();
}
}
// 使用
class Main {
public static void main(String[] args) {
YourExcelReader reader = new YourExcelReader();
reader.readExcel("C:\\Users\\28698\\Documents\\xxxxx.xlsx");
}
}