目录
- 表头示例
- 导入代码
- 数据导出
表头示例
导入代码
@Overridepublic 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;/*** 解析每一行表头数据时调用*/@Overridepublic void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {// 读取表头数据并构造HashMapif (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);}}}}/*** 每解析一条数据都会调用一次*/@Overridepublic 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了,需要去存储一次数据库,防止数据几万条数据在内存,容易OOMif (cachedDataList.size() >= BATCH_COUNT) {saveData();// 存储完成清理 listcachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);}}/*** 所有数据解析完成后调用*/@Overridepublic void doAfterAllAnalysed(AnalysisContext analysisContext) {if (!cachedDataList.isEmpty()){saveData();// 存储完成清理 listcachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);}}public void saveData(){//将数据存入数据库}}
数据导出
参考文章:EasyExcel动态复杂表头导出方法