尝试使用 POI-HSSF v3.2 解析MS Excel文件时我得到IndexOutOfBoundsException。我试图阅读的电子表格不是空的,它是使用MS Excel 2003创建的,POI包中包含的BiffViewer可以解析它。

我的代码如下:

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

这是我得到的堆栈跟踪:

<子> 线程“main”中的异常java.lang.IndexOutOfBoundsException         at java.io.FileInputStream.readBytes(Native Method)         在java.io.FileInputStream.read(FileInputStream.java:199)         在org.apache.poi.hssf.record.RecordInputStream.nextRecord(RecordInputStream.java:106)         在org.apache.poi.hssf.eventusermodel.HSSFRecordStream.getNextRecord(HSSFRecordStream.java:128)         在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)         在src.Excel.main(Excel.java:21)

非常感谢!我知道,我本来很懒,可以自己查看POI来源,但是,希望有人能够迅速指出我在代码中做过的任何愚蠢的事情。

有帮助吗?

解决方案

神秘解决了,获取输入流的正确方法如下

FileInputStream file   = new FileInputStream("c:\\temp\\a.xls");
POIFSFileSystem poifs  = new POIFSFileSystem(file);
InputStream     stream = poifs.createDocumentInputStream("Workbook");

其他提示

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());
  }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top