在发帖之前我搜索过但没有找到解决方案。
我有一个更大的 Excel 文件,可能是 .xls/xlsx,大小 > 10 MB。当我读取小的 Excel 文件时,它读取正常。但当它很大时,它会说内存/堆不足。有人说增加堆大小,但我认为这不是一个好的解决方案。 我正在上传 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 文件的解决方案是什么?我正在使用 apache POI API。
最佳答案
如果文件变得非常大并且可能总是超出您的可用内存,您可以查看 Apache POI 中的流 API,例如看https://poi.apache.org/spreadsheet/how-to.html#event_api
它附带了一个可立即运行的示例。
对于 .xlsx/XSSF 格式的文件,有一种类似的方法可以以更好的方式提供工作簿中的数据,请参阅 https://poi.apache.org/spreadsheet/how-to.html#xssf_sax_api
关于java - 如何读取上传后的大尺寸Excel文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37131556/