I want to read a large excel-file(.xlsx/.xls). When I upload a 20MB file, suddenly Java-Heap was increased by 2GB and ran into OutOfMemoryError.
private Sheet getSheetForFileType(String filType, InputStream fileData) throws IOException {
Workbook workbook;
Sheet sheet;
if (filType.equalsIgnoreCase("xls")) {
workbook = new HSSFWorkbook(fileData); //OutOfMemoryError
sheet = workbook.getSheetAt(0);
} else {
workbook = new XSSFWorkbook(fileData); //OutOfMemoryError
sheet = workbook.getSheetAt(0);
}
return sheet;
}
As mentioned here Apache-POI overview , I tried with XSSF and SAX (Event API) Modified code as below:
private Sheet getSheetForFileType(String filType, InputStream fileData) throws IOException {
if (filType.equalsIgnoreCase("xls")) {
....
} else {
OPCPackage opcPackage = OPCPackage.open(fileData); //OutOfMemoryError
XSSFReader xssfReader = new XSSFReader(opcPackage);
SharedStringsTable sharedStringsTable = xssfReader.getSharedStringsTable();
XMLReader parser = getSheetParser(sharedStringsTable);
....
....
}
return sheet;
}
Yet, I'm unable to load-file and read it.
I read file-data from Input-Stream, purpose is ONLY to Read-Data no write operations on it.
Reading a File takes lower memory, while an InputStream requires more memory as it has to buffer the whole file.
I went through other posts, what i understand:
- increase Heap Memory
- excel-streaming-reader [can't use, i've to support both(.xlsx/.xls)]
- read using SAX parser
Update-1: Added a sample-excel picture.
InputStream
when encounteringOutOfMemoryErrors
? Is this a viable option? Have you tried this? – Jonny HenlyOPCPackage.open(fileData)
leads to out of memory error, then you have no chance. But I really doubt that because it does nothing else than opening theZIP
archive of theOffice Open XML
*.xlsx
. That normally cannot lead to out of memory error. – Axel Richter