本文主要是介绍EasyExcel导出数据量大导致内存溢出,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一次性读入过多数据,如果内存不够大就会导致内存溢出,所以将数据分批处理,最后在EasyExcel导出的时候再汇总导出。至于接口耗时问题,就需要根据实际调整批次的最大数量。
/*** 全量导出工艺工时* @param response 请求信息*/@Overridepublic void exportEngineeringStandardWorkTime(HttpServletResponse response) {//获取需要导出的数据List<MoonStandardWorkTimeExportVO> moonStandardWorkTimeExportVOList = this.baseMapper.selectEngineeringStandardWorkTime();// 分批写入数据int batchSize = 100000; // 每批写入的数据量List<List<MoonStandardWorkTimeExportVO>> batchedData = splitIntoBatches(moonStandardWorkTimeExportVOList, batchSize);//导出数据try {String fileName = "设备工艺工时信息" + LocalDate.now();fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");WriteCellStyle contentWriteCellStyle = new WriteCellStyle();contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);EasyExcel.write(response.getOutputStream(), MoonStandardWorkTimeExportVO.class).registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).registerWriteHandler(new HorizontalCellStyleStrategy(new WriteCellStyle(), contentWriteCellStyle)).sheet("设备工艺工时信息").doWrite(batchedData.stream().flatMap(List::stream).collect(Collectors.toList()));} catch (IOException e) {throw new RuntimeException(e);}}/*** 将数据列表分割成多个小批量** @param dataList 数据列表* @param size 每个批次的大小* @return 分割后的数据列表*/private List<List<MoonStandardWorkTimeExportVO>> splitIntoBatches(List<MoonStandardWorkTimeExportVO> dataList, int size) {List<List<MoonStandardWorkTimeExportVO>> batches = new ArrayList<>();for (int i = 0; i < dataList.size(); i += size) {batches.add(dataList.subList(i, Math.min(i + size, dataList.size())));}return batches;}
这篇关于EasyExcel导出数据量大导致内存溢出的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!