title: How to lazily read big Excel 2007 files with Apache POI
body: <p>I'd like to read a big Excel 2007 file with Apache POI. <a href="http://poi.apache.org/spreadsheet/quick-guide.html#FileInputStream" rel="nofollow">Quick start guide</a> states that a <code>File</code> should be used to conserve memory.</p>
  
  <blockquote>
    <p>When opening a workbook, either a .xls HSSFWorkbook, or a .xlsx
    XSSFWorkbook, the Workbook can be loaded from either a File or an
    InputStream. Using a File object allows for lower memory consumption,
    while an InputStream requires more memory as it has to buffer the
    whole file.</p>
  </blockquote>
  
  <p>I therefore wrote approximately this:</p>
  
  <pre><code>opcPackage = OPCPackage.open(file);
  XSSFWorkbook workbook = new XSSFWorkbook(opcPackage);
  XSSFSheet sheet = workbook.getSheetAt(0);
  rows = sheet.rowIterator();
  if (rows.hasNext()) {
  Row row = rows.next();
      System.out.println(row.getCell(1).getStringCellValue());
  }
  </code></pre>
  
  <p>However that results in a <code>java.lang.OutOfMemoryError: Java heap space</code> for a sheet with more than approximately 10000 rows.</p>
  
  <p>I was hoping that iterating only lazily loads those rows that are to be read, like a stream. </p>
  
  <p>How can I get around memory issues with large Excel files? Can I read lazily with Apache POI?</p>