场景说明
Java实现Excel批量导入数据库
这个是之前已经实现的方式,细节点可以看之前的文章,主要是把之前使用POI的Workbook,替换为EasyExcel,提升性能
代码
1、继承AnalysisEventListener实现监听对象
public class ImportForlanStudentListener extends AnalysisEventListener<ForlanStudentExcelModule> {
private static final int maxRows = 5;
private static final String chineseHeader = "姓名\t年龄";
private List<ForlanStudentExcelModule> result = new ArrayList<>();
private boolean isErrorModule = false;
public List<ForlanStudentExcelModule> getResult() {
return result;
}
@Override
public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
if (CollectionUtils.isEmpty(headMap)) {
isErrorModule = true;
}
String headStr = headMap.values().stream().collect(Collectors.joining("\t"));
if (!headStr.equals(chineseHeader)) {
isErrorModule = true;
}
}
@Override
public void invoke(ForlanStudentExcelModule ForlanStudentExcelModule, AnalysisContext analysisContext) {
result.add(ForlanStudentExcelModule);
}
@Override
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
if (isErrorModule) {
throw new RuntimeException("请上传正确的模板文件");
}
if (CollectionUtils.isEmpty(result)) {
throw new RuntimeException("文件内容不能为空");
}
if (result.size() > maxRows) {
throw new RuntimeException(String.format("单次导入数据不能超过%s条", maxRows));
}
}
/**
* 返回false,表示没有下一条了
* 注意,这里返回false,doAfterAllAnalysed就不执行了
*/
// @Override
// public boolean hasNext(AnalysisContext analysisContext) {
// // 达到最大行数,不再解析下一条
// if(result.size() == maxRows){
// return false;
// }
// return true;
// }
}
2、EasyExcel解析Excel文件内容转为List对象
public List<ForlanStudent> processExcel(InputStream inputStream) {
List<ForlanStudent> forlanStudentList = new ArrayList<>();
ImportForlanStudentListener listener = new ImportForlanStudentListener();
EasyExcel.read(inputStream, ForlanStudentExcelModule.class, listener).sheet(0).doRead();
List<ForlanStudentExcelModule> result = listener.getResult();
BeanUtils.copyListProperties(result, forlanStudentList, ForlanStudent.class);
return forlanStudentList;
}
总结
我们对两种方式(POI、EasyExcel)进行了测试,测试结果
---------------------------------------------
ns % Task name
---------------------------------------------
512154000 002% EasyExcel读取1000.xlsx耗时
150298100 000% Poi读取1000.xlsx耗时
225033700 001% EasyExcel读取10000.xlsx耗时
285189600 001% Poi读取10000.xlsx耗时
879452400 003% EasyExcel读取100000.xlsx耗时
2136922200 007% Poi读取100000.xlsx耗时
5833847900 018% EasyExcel读取1000000.xlsx耗时
22367169200 069% Poi读取1000000.xlsx耗时
从结果可以看出,无论在1千、1万、10万、100万,EasyExcel的读取性能都更好
标签:xlsx,读取,EasyExcel,public,耗时,导入,result,数据库 From: https://www.cnblogs.com/huozhonghun/p/16962420.html