首先因为导出需要创建多个sheet页,而官方给得方法是将所有查询出来放进集合,然后调用方法,但是由于数据量大,全部查询出来,内存会溢出,所以要分页查询,然后分页。
然后想到使用ExcelBatchExportService,初始化时可以设置每个sheet最大row数量。
ExportParams exportParams = new ExportParams(title,null);
exportParams.setStyle(MyExcelExportStatisticStyler.class);
exportParams.setMaxNum(50000);//表示每页最多5W
ExcelBatchExportService exportService = new ExcelBatchExportService();
exportService.init(exportParams, cls);
当使用appendData方法添加的数量超过之后,将会新建一个sheet页面存放数据,问题就是这个时候产生的,如果设置了标题和表头,新建的sheet没有标题和表头,并且格式也不会保存下来。
看了半天源码,没有想到其他解决方案,一个个重新设置格式,感觉过于麻烦,然后想到了一个方法,把ExcelBatchExportService的源码拷出来,修改appendData方法。改成如图所示的样子就好
public Workbook appendDataCreateSheet(Collection<?> dataSet) {
//由此可以看出,这里判断如果超过最大值,就新建一个sheet
if (this.sheet.getLastRowNum() + dataSet.size() > this.entity.getMaxNum()) {
this.sheet = this.workbook.createSheet();
//添加重新生成表格样式方法
this.insertDataToSheet(this.workbook, entity, excelParams, (Collection)null, this.sheet);
//index根据不同的情况定,我的表头和标题有2行,设置的2
this.index = 2;
}
//下面不需要动
Iterator its = dataSet.iterator();
while(its.hasNext()) {
Object t = its.next();
try {
this.index += this.createCells(this.patriarch, this.index, t, this.excelParams, this.sheet, this.workbook, this.rowHeight, 0)[0];
} catch (Exception var5) {
LOGGER.error(var5.getMessage(), var5);
throw new ExcelExportException(ExcelExportEnum.EXPORT_ERROR, var5);
}
}
return this.workbook;
}
然后循环查询找里面直接调用就好了,注意这里调用你拷贝修改的类名。
for(){
...
List list = mapper.selectPage();
workbook = exportService.appendData(list);
...
}