简体   繁体   中英

Blocking Apache POI While Creating XSSFWorkbook

I am using apache POI 3.7 in JDK 1.5 Environment and -Xms256m -Xmx512m -XX:PermSize=64M -XX:MaxPermSize=1000M as JVM arguments.

I wrote the code to read xlsx file like this,

File file = new File("C:\\D\\Data Book.xlsx");
InputStream inputStream = new FileInputStream(file);
OPCPackage opcPackage = OPCPackage.open(inputStream);
XSSFWorkbook workbook = new XSSFWorkbook(opcPackage);

At the fourth line it is going into idle state. If I remove JVM arguments it is throwing OutOfMemoryError . My file size is 6MB.

If using OPCPackage is not essential then I would go for a straight instantiation:

InputStream inp = new FileInputStream("C:\\D\\Data Book.xlsx");
Workbook wb = WorkbookFactory.create(inp);

See the POI Quick Guide

If you have a file, then pass that in. Using an InputStream requires buffering of everything into memory, which eats up space. Since you don't need to do that buffering, don't!

If you're running with the latest nightly builds of POI, then it's very easy. Your code becomes:

File file = new File("C:\\D\\Data Book.xlsx");
OPCPackage opcPackage = OPCPackage.open(file);
XSSFWorkbook workbook = new XSSFWorkbook(opcPackage);

Otherwise, it's very similar:

File file = new File("C:\\D\\Data Book.xlsx");
OPCPackage opcPackage = OPCPackage.open(file.getAbsolutePath());
XSSFWorkbook workbook = new XSSFWorkbook(opcPackage);

It is hard to believe that this question wasn't answered for almost 8 years. I've posted the same answer to one of the similar questions, let me post it here as well. Instead of XSSFWorkbook (which keeps the entire Excel workbook in memory) try to use very efficient and high performance streaming SXSSFWorkbook class like below:

SXSSFWorkbook workbook = new SXSSFWorkbook(100);

where 100 is the default number of rows that will be kept in memory and processed in real time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM