2013-05-09 85 views
0

我想加载使用5张工作表的POI库的XLSX文件。该文件的大小是5 MB。所有工作表中的记录总数约为30,000。 一旦文件被加载,我需要基于表单neame作为输入来即时删除一个或多个表单。XLSX删除表OutOfMemory异常

以下是摘录。

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); 
     } 
    } 

当我执行程序。我得到OutofMemory异常。 如何删除没有内存问题的工作表。

+1

您的堆大小设置为?如果你关心内存,你为什么直接使用InputStream代替File? [文档清楚地指出File比InputStream使用更少的内存](http://poi.apache.org/spreadsheet/quick-guide.html#FileInputStream)... – Gagravarr 2013-05-09 17:30:42

+1

使用File而不是InputStream,你可以使用SXSSFWorkbook( )如果你有更多records.Workbook workBook = new SXSSFWorkbook(); – swamy 2013-05-10 07:03:01

回答

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; 
+2

请不要复制完全相同的帖子到几个问题 - 可能是他们不是真的适合所有问题或者问题是重复的(并且应该被标记为这样) – kleopatra 2013-10-20 09:04:59