JAVA - Out Of Memory Error while writing Excel Cel

2020-03-31 02:04发布

问题:

I am using JXL to write an excel file of 50000 rows and 30 columns. My code looks like this:

for (int j = 0; j < countOfRows; j++) {

myWritableSheet.addCell(new Label(0, j, myResultSet.getString(1), myWritableCellFormat));

myWritableSheet.addCell(new Label(1, j, myResultSet.getString(2), myWritableCellFormat));

.....

.....

}

While writing the cells, the program goes slower and slower

and finally around the row 25000 I am getting the following error:

Exception in thread "Thread-3" java.lang.OutOfMemoryError: Java heap space at jxl.write.biff.WritableSheetImpl.getRowRecord(WritableSheetImpl.java:984) at jxl.write.biff.WritableSheetImpl.addCell(WritableSheetImpl.java:951) at KLL.ConverterMainFrame$exportToXLSBillRightsThread.run(ConverterMainFrame.java:6895)

It's always difficult in Java to handle the memory.

In this case it seems to be the jxl's problem.

Is there a way to write the file, clear the memory and coninue writing cells every 1000 cells?

Would that be a good idea or what else would you propose as a solution?

回答1:

Is raising the memory available to the VM (with -Xms and -Xmx) not an option?



回答2:

The JExcel FAQ has a couple of suggestions including Curtis' idea above.

If you don't mind the performance hit, you could use a temporary file instead of doing it all in memory.

WorkbookSettings s = new WorkbookSettings();  
s.setUseTemporaryFileDuringWrite(true);  
WritableWorkbook ws = Workbook.createWorkbook(new File("someFile.xls"),s);