package com.chinaztt.mes.technology.excel;
|
|
import com.alibaba.excel.context.AnalysisContext;
|
import com.alibaba.excel.event.AnalysisEventListener;
|
import com.chinaztt.mes.technology.service.RoutingService;
|
import lombok.extern.slf4j.Slf4j;
|
|
import java.util.ArrayList;
|
import java.util.HashMap;
|
import java.util.List;
|
import java.util.Map;
|
|
/**
|
* @Author: liuth
|
* @Date: 2020-11-30 9:46
|
*/
|
@Slf4j
|
public class RoutingFormUploadListener extends AnalysisEventListener<Map<Integer, String>> {
|
|
private static final int BATCH_COUNT = 10000;
|
// List<RoutingData> list = new ArrayList<>();
|
|
private List<String> errMessage;
|
//用list集合保存解析到的结果
|
// private List<Map<Integer, Map<Integer, String>>> list;
|
// private Map<Integer, Map<Integer, String> map;
|
|
/**
|
* 表头数据
|
*/
|
private Map<Integer, String> headMap = new HashMap<>();
|
/**
|
* 数据体
|
*/
|
private List<Map<Integer, String>> dataList = new ArrayList<>();
|
|
private RoutingService routingService;
|
|
public RoutingFormUploadListener(RoutingService routingService) {
|
this.routingService = routingService;
|
}
|
|
|
/**
|
* 重写invokeHeadMap方法,获去表头,如果有需要获取第一行表头就重写这个方法,不需要则不需要重写
|
* @param headMap 每行解析的数据为Map<Integer, String>类型,Integer是Excel的列索引,String为Excel的单元格值
|
* @param context context能获取一些东西,比如context.readRowHolder().getRowIndex()为Excel的行索引,表头的行索引为0,0之后的都解析成数据
|
*/
|
@Override
|
public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
|
// super.invokeHeadMap(headMap, context);
|
log.info("解析到一条头数据:{}, currentRowHolder: {}", headMap.toString(), context.readRowHolder().getRowIndex());
|
// Map<Integer, Map<Integer, String>> map = new HashMap<>();
|
// map.put(context.readRowHolder().getRowIndex(), headMap);
|
// list.add(map);
|
// map.put(context.readRowHolder().getRowIndex(), headMap);
|
this.headMap = headMap;
|
// headMap.putAll(paramMap1);
|
}
|
|
|
|
/**
|
* 重写invoke方法获得除Excel第一行表头之后的数据
|
* 如果Excel第二行也是表头,那么也会解析到这里,如果不需要就通过判断context.readRowHolder().getRowIndex()跳过
|
* @param data
|
* @param analysisContext
|
*/
|
@Override
|
public void invoke(Map<Integer, String> data, AnalysisContext analysisContext) {
|
log.info("解析到一条数据:{}, currentRowIndex: {}----", data.toString(), analysisContext.readRowHolder().getRowIndex());
|
dataList.add(data);
|
if (dataList.size() >= BATCH_COUNT) {
|
save();
|
dataList.clear();
|
}
|
}
|
|
/**
|
* 解析到最后会进入这个方法,需要重写这个doAfterAllAnalysed方法,然后里面调用自己定义好保存方法
|
* @param analysisContext
|
*/
|
@Override
|
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
|
save();
|
log.info("所有数据解析完成!");
|
}
|
|
|
private void save() {
|
routingService.importExcelExt(headMap, dataList);
|
}
|
}
|