转自:http://t.zoukankan.com/pzw23-p-13354908.html
-
easyexcel导入获取表头并且表头为不固定列
Controller
@PostMapping("upload") @ResponseBody public HashMap<String, Object> upload(@RequestParam(value = "file") MultipartFile file, @RequestParam(value = "ztId") int ztId, @RequestParam(value = "qj") String qj, @RequestParam(value = "gzlbId") String gzlbId) throws IOException { gzdrService.init(ztId, qj, gzlbId); //生成uuid String uuid = UUID.randomUUID().toString(); GzdrListener gzdrListener = new GzdrListener(ztId, gzdrService, uuid, qj, gzlbId); EasyExcel.read(file.getInputStream(), gzdrListener).sheet("导入模板").doReadSync(); HashMap<String, Object> hashMap = new HashMap<>(); List<String> errMessage = gzdrListener.getErrMessage(); if (errMessage.isEmpty()) { hashMap.put("success", true); } else { hashMap.put("success", false); hashMap.put("errMessage", errMessage); } return hashMap; }
GzdrListener
public class GzdrListener extends AnalysisEventListener<Map<Integer, String>> { /** * 每隔128条存储数据库,然后清理list ,方便内存回收 */ private static final int BATCH_COUNT = 128; private int ztId; private List<String> errMessage; private GzdrService gzdrService; List<Map<Integer, String>> list = new ArrayList<Map<Integer, String>>(); private String uuid; private String qj; private String gzlbId; public GzdrListener(int ztId, GzdrService gzdrService, String uuid, String qj, String gzlbId) { this.ztId = ztId; this.gzdrService = gzdrService; this.uuid = uuid; this.qj = qj; this.gzlbId = gzlbId; errMessage = new ArrayList<>(); } @Override public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) { logger.info("解析到一条头数据:{}, currentRowHolder: {}", headMap.toString(), context.readRowHolder().getRowIndex()); list.add(headMap); } @Override public void invoke(Map<Integer, String> data, AnalysisContext context) { logger.info("解析到一条数据:{}, currentRowHolder: {}", data.toString(), context.readRowHolder().getRowIndex()); list.add(data); // 达到BATCH_COUNT了,需要去存储一次数据库,防止数据几万条数据在内存,容易OOM if (list.size() >= BATCH_COUNT) { errMessage.addAll(saveData()); // 存储完成清理 list list.clear(); } } @Override public void doAfterAllAnalysed(AnalysisContext context) { // 这里也要保存数据,确保最后遗留的数据也存储到数据库 errMessage.addAll(saveData()); logger.info("所有数据解析完成!"); } /** * 加上存储数据库 */ private List<String> saveData() { logger.info("{}条数据,开始存储数据库!,ztId:{} ", list.size(), ztId); return gzdrService.save(list, ztId, uuid, qj, gzlbId); } public List<String> getErrMessage() { return errMessage; } public void setErrMessage(List<String> errMessage) { this.errMessage = errMessage; } public GzdrService getGzdrService() { return gzdrService; } public void setGzdrService(GzdrService gzdrService) { this.gzdrService = gzdrService; } private final static Logger logger = LoggerFactory.getLogger(GzdrListener.class); }
- 原文地址:https://www.cnblogs.com/pzw23/p/13354908.html