java 65533,java导出excel超出65533行

业务背景:

列表导出,数据导出超过65533行

解决方案:

1、超出65533行,直接系统提示:本系统支持导出的最大条数为65533行

2、导出模版改为.xlsx,POI导出时用XSSFWorkbook,把所有数据都拿到内存里,可以导出超过65533行,但是上线之后,发现会内存溢出

3、导出模版改为.xlsx,POI导出时用SXSSFWorkbook,每次往内存里放一定的数据,导完之后,刷新,再次从磁盘往内存放数据,会产生临时文件,导出完成之后,需把临时文件删掉,这种方式会使CPU短暂升高,但是很快会降下去

private static ByteArrayInputStream WriteToExcelTemplate(DataModel dataModel, HttpServletRequest request) {

String template = getRealPathModelExcel(dataModel.getTemplate(), request);

FileInputStream fileInputStream = new FileInputStream(template);

XSSFWorkbook workBook = new XSSFWorkbook(fileInputStream);

int rowaccess = 100;

SXSSFWorkbook wb = new SXSSFWorkbook(workBook,rowaccess);

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

Sheet sh = wb.getSheetAt(0);

List data = dataModel.getData();

int startRow = dataModel.getStartRow();

for (int i = 0; i < data.size(); ++i) {

Object[] objArray = (Object[]) data.get(i);

Row row = sh.createRow(startRow);

Cell[] cell = new SXSSFCell[objArray.length];

for (int j = 0; j < objArray.length; ++j) {

cell[j] = row.createCell(j);

cell[j].setCellStyle(dataModel.getCenterStyle());

if (objArray[j] == null) {

cell[j].setCellValue("");

} else {

setCellValue(cell[j], objArray[j]);

}

}

++startRow;

if(i%rowaccess==0){

((SXSSFSheet)sh).flushRows();

}

}

wb.write(byteArrayOutputStream);

byte[] byteArray = byteArrayOutputStream.toByteArray();

ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArray);

byteArrayOutputStream.close();

deleteSXSSFTempFiles(wb);//删除临时文件

return byteArrayInputStream;

}

/**

* 删除临时文件

* @param workbook

* @throws NoSuchFieldException

* @throws IllegalAccessException

*/

public static void deleteSXSSFTempFiles(SXSSFWorkbook workbook)

throws NoSuchFieldException, IllegalAccessException {

int numberOfSheets = workbook.getNumberOfSheets();

// iterate through all sheets (each sheet as a temp file)

for (int i = 0; i < numberOfSheets; i++) {

Sheet sheetAt = workbook.getSheetAt(i);

// delete only if the sheet is written by stream

if (sheetAt instanceof SXSSFSheet) {

SheetDataWriter sdw = (SheetDataWriter) getPrivateAttribute(sheetAt, "_writer");

File f = (File) getPrivateAttribute(sdw, "_fd");

try {

f.delete();

} catch (Exception ex) {

// could not delete the file

}

}

}

}

public static Object getPrivateAttribute(

Object containingClass, String fieldToGet)

throws NoSuchFieldException, IllegalAccessException{

// get the field of the containingClass instance

Field declaredField = containingClass.getClass().getDeclaredField(fieldToGet);

declaredField.setAccessible(true); // access it

Object get = declaredField.get(containingClass); // return it!

return get;

}

标签:java,get,int,导出,Object,excel,cell,new,65533

来源: https://blog.csdn.net/weixin_43805526/article/details/90415248

你可能感兴趣的:(java,65533)