表头示例
文章来源:https://www.toymoban.com/news/detail-742286.html
导入代码
@Override
public void importExcel(InputStream inputStream) {
ItemExcelListener itemExcelListener = new ItemExcelListener();
EasyExcel.read(inputStream, ImportItem.class, itemExcelListener).headRowNumber(2).sheet().doRead();
}
@Slf4j
public class ItemExcelListener extends AnalysisEventListener<ImportItem> {
/**
* 定义100条数据存储一次,然后清理list,方便内存回收
*/
private static final int BATCH_COUNT = 300;
/**
* 记录导入的总记录数
*/
private Long listSize = 0L;
/**
* 缓存的数据
*/
private List<ImportItem> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
//标记处理第一行表头
private boolean firstRowProcessed = true;
private HashMap<Integer, HashMap<String,String>> dynamicInfoList;
/**
* 解析每一行表头数据时调用
*/
@Override
public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
// 读取表头数据并构造HashMap
if (firstRowProcessed){
HashMap<Integer, HashMap<String, String>> infoList = new HashMap<>();
for (Map.Entry<Integer, String> entry : headMap.entrySet()){
Integer key = entry.getKey();
String value = entry.getValue();
if (!Objects.equals(value, "固定数据")){
infoList.put(key,null);
}
}
dynamicInfoList = infoList;
firstRowProcessed = false;
}else {
for (Map.Entry<Integer, String> entry : headMap.entrySet()){
HashMap<String, String> info = new HashMap<>();
Integer key = entry.getKey();
String value = entry.getValue();
if (dynamicInfoList.containsKey(key)){
info.put(value,null);
dynamicInfoList.replace(key,info);
}
}
}
}
/**
* 每解析一条数据都会调用一次
*/
@Override
public void invoke(ImportItem importItem, AnalysisContext analysisContext) {
// 获取实体类中不匹配的数据
ReadRowHolder readRowHolder = analysisContext.readRowHolder();
Map<Integer, Cell> cellMap = readRowHolder.getCellMap();
JSONObject dynamicInformation = new JSONObject();
for (Map.Entry<Integer, Cell> entry : cellMap.entrySet()){
Integer key = entry.getKey();
Cell entryValue = entry.getValue();
if (dynamicInfoList.containsKey(key)){
String string = JSON.toJSONString(entryValue);
JSONObject jsonObject = JSON.parseObject(string);
String value = jsonObject.getString("stringValue");
HashMap<String, String> info = dynamicInfoList.get(key);
for (String attribute : info.keySet()) {
dynamicInformation.put(attribute,value);
}
}
}
cachedDataList.add(importItem);
// 达到BATCH_COUNT了,需要去存储一次数据库,防止数据几万条数据在内存,容易OOM
if (cachedDataList.size() >= BATCH_COUNT) {
saveData();
// 存储完成清理 list
cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
}
}
/**
* 所有数据解析完成后调用
*/
@Override
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
if (!cachedDataList.isEmpty()){
saveData();
// 存储完成清理 list
cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
}
}
public void saveData(){
//将数据存入数据库
}
}
数据导出
参考文章:EasyExcel动态复杂表头导出方法文章来源地址https://www.toymoban.com/news/detail-742286.html
到了这里,关于EasyExcel复杂表头数据导入的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!