上传后如何读取大尺寸的excel文件

发布之前,我search,但没有得到解决scheme。

我有一个更大的Excel文件可能是> 10 MB的.xls / xlsx。 当我正在阅读小excel文件,然后它确定。 但是,如果它的内存/堆大小的话。 有人说增加堆大小,但我认为这不是一个好的解决scheme。 我正在上传Excel文件和阅读为:

byte b[] = file.getBytes(); InputStream ips = new ByteArrayInputStream(b); Workbook workbook = WorkbookFactory.create(ips); Sheet sheet = workbook.getSheetAt(0); // ============ int i = 0; List<String> colName = new ArrayList<>(); Map<Integer, Object> lhm = null; Iterator<Row> rowIterator = sheet.iterator(); while (rowIterator.hasNext()) { lhm = new LinkedHashMap<>(); Row row = rowIterator.next(); // For each row, iterate through all the columns Iterator<Cell> cellIterator = row.cellIterator(); while (cellIterator.hasNext()) { Cell cell = cellIterator.next(); // Check the cell type and format accordingly switch (cell.getCellType()) { case Cell.CELL_TYPE_NUMERIC: // System.out.print(cell.getNumericCellValue() + "--"); if (DateUtil.isCellDateFormatted(cell)) { lhm.put(cell.getColumnIndex(), Utils.getDateStringFromString(cell.getDateCellValue().toString(), "yyyy-MM-dd")); } else { lhm.put(cell.getColumnIndex(), String.valueOf(cell.getNumericCellValue())); } break; case Cell.CELL_TYPE_STRING: if (i == 0) { colName.add(cell.getStringCellValue()); } else { // System.out.print(cell.getStringCellValue() + // "=="); lhm.put(cell.getColumnIndex(), cell.getStringCellValue()); } break; case Cell.CELL_TYPE_BOOLEAN: // System.out.print(cell.getBooleanCellValue() + "--"); lhm.put(cell.getColumnIndex(), String.valueOf(cell.getBooleanCellValue())); break; } } 

此代码不适用于大型Excel文件。 两个xls / xlsx文件的解决scheme是什么? 我正在使用Apache的POI API。

如果文件可能变得非常庞大,并且可能总是超过可用内存,那么可以参考Apache POI中的streaming-API,例如,查看https://poi.apache.org/spreadsheet/how-to.html# event_api

它带有一个现成的例子。

对于.xlsx / XSSF格式的文件,还有一种类似的方式,以更好的方式提供工作簿中的数据,请参阅https://poi.apache.org/spreadsheet/how-to.html#xssf_sax_api