2012-09-26 25 views
1

当我尝试初始化一个工作簿对象,我总是得到这个错误:为什么我未能使用POI读取Excel 2007?

The supplied data appears to be in the Office 2007+ XML. You are calling the part of POI that deals with OLE2 Office Documents. You need to call a different part of POI to process this data (eg XSSF instead of HSSF) 

但我跟着办公样品要做到这一点,下面是我的代码:

File inputFile = new File(inputFileName); 
InputStream is = new FileInputStream(inputFile); 
Workbook wb = new XSSFWorkbook(is); 

异常出现在代码行:

Workbook wb = new XSSFWorkbook(is); 

下面是POI JAR包括:

poi-3.8-20120326.jar 
poi-ooxml-3.8-20120326.jar 
poi-ooxml-schemas-3.8-20120326.jar 
xmlbeans-2.3.0.jar 

任何人都可以给我指导吗?显示如何阅读完整的Excel 2007文档的示例将不胜感激。提前致谢!

回答

3

我认为你已经重新检查过你的原始文件确实是Office 2007 + XML格式的,对不对?

编辑:

然后,如果您确定的格式是确定的,而且它使用WorkbookFactory.create为你工作,你可以找到在这种方法的代码的答案:

/** 
    * Creates the appropriate HSSFWorkbook/XSSFWorkbook from 
    * the given InputStream. 
    * Your input stream MUST either support mark/reset, or 
    * be wrapped as a {@link PushbackInputStream}! 
    */ 
    public static Workbook create(InputStream inp) throws IOException, InvalidFormatException { 
      // If clearly doesn't do mark/reset, wrap up 
      if(! inp.markSupported()) { 
        inp = new PushbackInputStream(inp, 8); 
      } 

      if(POIFSFileSystem.hasPOIFSHeader(inp)) { 
        return new HSSFWorkbook(inp); 
      } 
      if(POIXMLDocument.hasOOXMLHeader(inp)) { 
        return new XSSFWorkbook(OPCPackage.open(inp)); 
      } 
      throw new IllegalArgumentException("Your InputStream was neither an OLE2 stream, nor an OOXML stream"); 
    } 

这是你丢失的那一点:new XSSFWorkbook(OPCPackage.open(inp))

+0

我觉得我的Excel源代码没有问题。 –

+0

解决。我可以通过以下代码阅读: File inputFile = new File(inputFileName); Workbook wb = WorkbookFactory.create(new FileInputStream(inputFile)); 即使它工作,我不知道下面和上面的代码之间有什么区别。 –

+0

看到我上面编辑的答案 –

相关问题