在Java中读取.xlsx文件非常大

时间:2014-07-31 15:37:09

标签: java apache-poi

我正在使用Java开发Web应用程序,我有一个方法应该使用 apache-poi 读取 .xlsx 文件:

public static void xlsx(String arquivo) throws IOException{

     try {
        FileInputStream file = new FileInputStream(new File(arquivo));
        XSSFWorkbook workbook = new XSSFWorkbook(file);
        XSSFSheet sheet = workbook.getSheetAt(0);
        Iterator<Row> rowIterator = sheet.iterator();
        while (rowIterator.hasNext()) {
            Row row = rowIterator.next();
            Iterator<Cell> cellIterator = row.cellIterator();
            while (cellIterator.hasNext()) {
                Cell celula = cellIterator.next();
                /*here do the reading for each cell,*/
            }
        }
        file.close();

    } catch (IOException e) {
        e.printStackTrace();
        throw new IOException("Erro ao processar arquivo.",e.getCause());
    }
}

该方法正常工作,但该方法处理具有数千行记录的文件的可能性有多大,例如,大约25-300万行。处理大文件时,我采用以下异常:

(http-localhost-127.0.0.1-8080-4) Servlet.service() for servlet RestServlet threw exception: org.jboss.resteasy.spi.UnhandledException: java.lang.OutOfMemoryError: Java heap space

我需要知道如何避免这种类型的错误。例如,如果您有,请阅读并处理文件 .xlsx 1000到1000行,或其他解决方案。

1 个答案:

答案 0 :(得分:1)

如果要保留现有实现,只需增加JVM最大堆大小即可。 有关说明和相关讨论,请参阅How to increase heap size for jBoss server

相关问题