0

我正在尝试使用具有 5 张纸的 POI 库加载 XLSX 文件。文件大小为 5 MB。所有工作表中的总记录约为 30,000。加载文件后,我需要根据工作表名称作为输入动态删除 1 张或多张工作表。

这是片段。

 public void generateReportWorkBook(String[] requestedReports) throws Exception {
      // Read the file
      String dailyTicketReport = ReportConstants.REPORT_PATH + ReportConstants.FILE_NAME + ReportConstants.XLSX_FILE_EXTN;

      FileInputStream fis = null;
      XSSFWorkbook book  = null;

      try {
          fis = new FileInputStream(dailyTicketReport);

          book = new XSSFWorkbook(fis);
          for (int i = book.getNumberOfSheets() - 1; i >= 0; i--) {
              XSSFSheet tmpSheet = book.getSheetAt(i);
              if (!ArrayUtils.contains(requestedReports, tmpSheet.getSheetName())) {
                  book.removeSheetAt(i);
              }
          }
      } catch (Exception e) {
          logger.error("Error occured while removing the sheets from workbook");
          throw e;
      } finally {
          IOUtils.closeQuietly(fis);
      }
    }  

当我执行程序时。我得到内存不足异常。如何在没有内存问题的情况下移除床单。

4

1 回答 1

0

我在解析xlsx文件时也遇到了同样的OOM问题……经过两天的努力,我终于发现下面的代码非常完美;

此代码基于 sjxlsx。它读取 xlsx 并存储在 HSSF 表中。

            // read the xlsx file
       SimpleXLSXWorkbook = new SimpleXLSXWorkbook(new File("C:/test.xlsx"));

        HSSFWorkbook hsfWorkbook = new HSSFWorkbook();

        org.apache.poi.ss.usermodel.Sheet hsfSheet = hsfWorkbook.createSheet();

        Sheet sheetToRead = workbook.getSheet(0, false);

        SheetRowReader reader = sheetToRead.newReader();
        Cell[] row;
        int rowPos = 0;
        while ((row = reader.readRow()) != null) {
            org.apache.poi.ss.usermodel.Row hfsRow = hsfSheet.createRow(rowPos);
            int cellPos = 0;
            for (Cell cell : row) {
                if(cell != null){
                    org.apache.poi.ss.usermodel.Cell hfsCell = hfsRow.createCell(cellPos);
                    hfsCell.setCellType(org.apache.poi.ss.usermodel.Cell.CELL_TYPE_STRING);
                    hfsCell.setCellValue(cell.getValue());
                }
                cellPos++;
            }
            rowPos++;
        }
        return hsfSheet;
于 2013-10-20T07:49:49.367 回答