使用手册:https://www.yuque.com/easyexcel/doc/easyexcel
主要注意的点就是修改监听器为通用的监听器
原监听器:
import java
.util
.ArrayList
;
import java
.util
.List
;
import demo
.DemoData
;
import org
.slf4j
.Logger
;
import org
.slf4j
.LoggerFactory
;
import com
.alibaba
.excel
.context
.AnalysisContext
;
import com
.alibaba
.excel
.event
.AnalysisEventListener
;
import com
.alibaba
.fastjson
.JSON
;
public class DemoDataListener extends AnalysisEventListener<DemoData> {
private static final Logger LOGGER
= LoggerFactory
.getLogger(DemoDataListener
.class);
private static final int BATCH_COUNT
= 5;
List
<DemoData> list
= new ArrayList<DemoData>();
private DemoDAO demoDAO
;
public DemoDataListener() {
}
public DemoDataListener(DemoDAO demoDAO
) {
this.demoDAO
= demoDAO
;
}
@Override
public void invoke(DemoData data
, AnalysisContext context
) {
LOGGER
.info("解析到一条数据:{}", JSON
.toJSONString(data
));
list
.add(data
);
if (list
.size() >= BATCH_COUNT
) {
saveData();
list
.clear();
}
}
@Override
public void doAfterAllAnalysed(AnalysisContext context
) {
saveData();
LOGGER
.info("所有数据解析完成!");
}
private void saveData() {
LOGGER
.info("{}条数据,开始存储数据库!", list
.size());
demoDAO
.save(list
);
LOGGER
.info("存储数据库成功!");
}
}
通用监听器:
import java
.util
.ArrayList
;
import java
.util
.List
;
import demo
.DemoData
;
import org
.slf4j
.Logger
;
import org
.slf4j
.LoggerFactory
;
import com
.alibaba
.excel
.context
.AnalysisContext
;
import com
.alibaba
.excel
.event
.AnalysisEventListener
;
import com
.alibaba
.fastjson
.JSON
;
public class DemoDataListener extends AnalysisEventListener {
private static final Logger LOGGER
= LoggerFactory
.getLogger(DemoDataListener
.class);
private static final int BATCH_COUNT
= 5;
List
<Object> list
= new ArrayList<Object>();
private DemoDAO demoDAO
;
public DemoDataListener() {
}
public DemoDataListener(DemoDAO demoDAO
) {
this.demoDAO
= demoDAO
;
}
@Override
public void invoke(Object data
, AnalysisContext context
) {
LOGGER
.info("解析到一条数据:{}", JSON
.toJSONString(data
));
list
.add(data
);
if (list
.size() >= BATCH_COUNT
) {
saveData();
list
.clear();
}
}
@Override
public void doAfterAllAnalysed(AnalysisContext context
) {
saveData();
LOGGER
.info("所有数据解析完成!");
}
private void saveData() {
LOGGER
.info("{}条数据,开始存储数据库!", list
.size());
LOGGER
.info("存储数据库成功!");
}
}
转载请注明原文地址:https://tech.qufami.com/read-12714.html