简体   繁体   English

创建 XSSFWorkbook 时阻止 Apache POI

[英]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.我在 JDK 1.5 环境中使用 apache POI 3.7 和-Xms256m -Xmx512m -XX:PermSize=64M -XX:MaxPermSize=1000M作为 JVM 参数。

I wrote the code to read xlsx file like this,我写了这样的代码来读取xlsx文件,

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 .如果我删除 JVM 参数,它会抛出OutOfMemoryError My file size is 6MB.我的文件大小是 6MB。

If using OPCPackage is not essential then I would go for a straight instantiation:如果使用OPCPackage不是必需的,那么我会直接实例化:

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

See the POI Quick Guide查看POI 快速指南

If you have a file, then pass that in. Using an InputStream requires buffering of everything into memory, which eats up space.如果您有文件,则将其传入。使用 InputStream 需要将所有内容缓冲到内存中,这会占用空间。 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.如果您正在运行最新的夜间构建的 POI,那么这很容易。 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.很难相信这个问题已经将近 8 年没有人回答了。 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 类,而不是 XSSFWorkbook(将整个 Excel 工作簿保存在内存中),如下所示:

SXSSFWorkbook workbook = new SXSSFWorkbook(100);

where 100 is the default number of rows that will be kept in memory and processed in real time.其中 100 是将保存在内存中并实时处理的默认行数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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