一次性读入过多数据,如果内存不够大就会导致内存溢出,所以将数据分批处理,最后在EasyExcel导出的时候再汇总导出。至于接口耗时问题,就需要根据实际调整批次的最大数量。
java
/**
* 全量导出工艺工时
* @param response 请求信息
*/
@Override
public 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;
}