0

Whilst trying to parse MS Excel file using POI-HSSF v3.2 I am getting IndexOutOfBoundsException. The spreadsheet I am trying to read isn't empty it has been created using MS Excel 2003 and BiffViewer included with the POI package has no problem parsing it.

My code is as follows:

package src;

import java.io.*;
import org.apache.poi.hssf.record.*;
import org.apache.poi.hssf.eventusermodel.*;

class Excel implements HSSFListener
{
    public static void main (String[] args) throws Exception
    {
        FileInputStream stream = new FileInputStream("c:\\temp\\a.xls");


        HSSFEventFactory f = new HSSFEventFactory();

        HSSFRequest req = new HSSFRequest();

        req.addListenerForAllRecords(new Excel());

        f.processEvents(req,stream);

        stream.close();
    }

    public void processRecord (Record r)
    {
        System.out.println(r);
    }
}

And here is the stack trace I am getting:

Exception in thread "main" java.lang.IndexOutOfBoundsException at java.io.FileInputStream.readBytes(Native Method) at java.io.FileInputStream.read(FileInputStream.java:199) at org.apache.poi.hssf.record.RecordInputStream.nextRecord(RecordInputStream.java:106) at org.apache.poi.hssf.eventusermodel.HSSFRecordStream.getNextRecord(HSSFRecordStream.java:128) at org.apache.poi.hssf.eventusermodel.HSSFRecordStream.nextRecord(HSSFRecordStream.java:93) at org.apache.poi.hssf.eventusermodel.HSSFEventFactory.genericProcessEvents(HSSFEventFactory.java:141) at org.apache.poi.hssf.eventusermodel.HSSFEventFactory.processEvents(HSSFEventFactory.java:98) at src.Excel.main(Excel.java:21)

Many thanks! I know, I am being plain lazy and could have looked at the POI source myself, but, hopefully, someone here will be able to point out swiftly whatever silly thing I've done within my code.

2 Answers 2

2

Mystery solved, the correct way of getting an input stream is as follows

FileInputStream file   = new FileInputStream("c:\\temp\\a.xls");
POIFSFileSystem poifs  = new POIFSFileSystem(file);
InputStream     stream = poifs.createDocumentInputStream("Workbook");
2
FileInputStream stream =
   new FileInputStream("abcd.xls");  
  HSSFEventFactory f = new HSSFEventFactory(); 
  HSSFRequest req = new HSSFRequest(); 
  req.addListenerForAllRecords(new Excel());  
  Workbook wb;
  wb = new HSSFWorkbook(stream); 
  Sheet sheet=wb.getSheet("abcd11042009");
  int rows=sheet.getPhysicalNumberOfRows();
  Row headerRow;
  Cell cell;
  for(int i=0;i<rows;i++)
  {
    headerRow= sheet.getRow(i);

    cell = headerRow.getCell(1);
    System.out.println("Doing..."+ cell.getStringCellValue());
  }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.