快速上手
引入依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.1.0</version>
</dependency>
public static void main(String[] args) {
final List<DataDemoVO> list = new LinkedList<DataDemoVO>();
EasyExcel.read("C:\\Desktop\\key_part.xlsx")
.head(DataDemoVO.class)
.sheet().registerReadListener(new AnalysisEventListener<DataDemoVO>() {
public void invoke(DataDemoVO dataDemoVO, AnalysisContext analysisContext) {
list.add(dataDemoVO);
}
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
System.out.println("数据读取完毕");
}
}).doRead();
for (DataDemoVO excelData : list) {
System.out.println("--->" + excelData);
}
}
封装(让代码更可用)
/**
* @author: lpy
* @Date: 2023/01/12
*/
@Slf4j
public class ExcelUtils {
/**
* Excel模板
*
* 名字 | 日期 | 年龄
* name | 2023 | 13
* name2 | 2024 | 15
* name3 | 2025 | 16
*
* 实体类配合注解 @ExcelProperty("字符串标题")
*
* url: https://easyexcel.opensource.alibaba.com/docs/current/quickstart/read
*/
/**
* file 前端传过来的文件流
* clazz 要转换的实体类类型
*/
public static <T> List<T> importExcel(MultipartFile file, Class<T> clazz) {
T t = null;
final List<T> list = new LinkedList<T>();
try {
t = clazz.newInstance();
EasyExcel.read(file.getInputStream())
.head(clazz)
.sheet().registerReadListener(new AnalysisEventListener<T>() {
@Override
public void invoke(T t, AnalysisContext analysisContext) {
list.add(t);
}
@Override
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
log.info("{} 数据读取完毕", file.getOriginalFilename());
}
}).doRead();
return list;
} catch (Exception e) {
e.printStackTrace();
return new LinkedList<T>();
}
}
// 或者
public static <T> List<T> importExcel2(MultipartFile file, Class<T> clazz) {
T t = null;
final List<T> list = new LinkedList<T>();
try {
t = clazz.newInstance();
EasyExcel.read(file.getInputStream(),
new ReadListener<T>() {
@Override
public void invoke(T t, AnalysisContext analysisContext) {
list.add(t);
}
@Override
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
log.info("{} 数据读取完毕", file.getOriginalFilename());
}
}).sheet().doRead();
return list;
} catch (Exception e) {
e.printStackTrace();
return new LinkedList<T>();
}
}
}
Exception
如果报错com.alibaba.excel.exception.ExcelAnalysisException: java.lang.NoSuchMethodError
那就是poi版本依赖问题,解决一下依赖,或者删除掉之前的poi