为什么我无法使用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); 

代码行发生exception:

 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文档的示例将不胜感激。 提前致谢!

我假设你重新检查你的原始文件确实是Office 2007 + XML格式,对不对?

编辑:

然后,如果您确定格式正确,并且适​​用于您使用WorkbookFactory.create,则可以在此类方法的代码中find答案:

  /** * 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"); } 

这是你所缺less的一点: new XSSFWorkbook(OPCPackage.open(inp))