首页 文章

在Apache POI中强制只读第一张表

提问于
浏览
0

我正在使用Apache POI仅在excel文件的第一张表中读取数据 . 提交的xlsx文件通常只有1张,大约2.5MB(数据行数超过130k),一切都很慢,但没有错误 . 但是,如果提交的xlsx有多个工作表,并且其他工作表中也包含大量数据,则执行会抛出OutOfMemoryError:Java堆空间错误 . 现在我想弄清楚它是否可能总是只读取第一张表上的数据而不用担心内存错误(我用-Xmx1024m -Xms512m参数运行它)

编辑:这是我的代码

InputStream inputStream = new FileInputStream(new File(excelfile));
XSSFWorkbook workbook = new XSSFWorkbook(inputStream);

    if (workbook.getNumberOfSheets() != 1) {
      throw new Exception("Make sure excel only has 1 sheet");
    }

该程序在第二行引发错误(如果excel文件在第二张表上也有很多数据)

1 回答

  • 2

    Apache POI通常会触发很多与内存相关的问题,我强烈建议使用monitorjbs而不是https://github.com/monitorjbl/excel-streaming-reader

    InputStream is = new FileInputStream(new File(filePath));
                    Workbook workbook = StreamingReader.builder()
                            .rowCacheSize(100) // number of rows to keep in memory (defaults to 10)
                            .bufferSize(2048) // buffer size to use when reading InputStream to file (defaults to 1024)
                            .open(is)) {
    
                Sheet sheet = workbook.getSheetAt(0);
    

相关问题