1

当我尝试初始化 Workbook 对象时,我总是收到此错误:

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

4

1 回答 1

4

我假设您已经重新检查您的原始文件确实是 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))

于 2012-09-26T02:37:03.553 回答