java 为什么我无法使用 POI 读取 Excel 2007?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12593752/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 09:28:00  来源:igfitidea点击:

Why do I failed to read Excel 2007 using POI?

javaexcelapache-poi

提问by Brady Zhu

When I try to initialize a Workbook object I always get this error:

当我尝试初始化 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)

But I followed the office sample to do this, following is my code:

但是我按照office sample来做这个,下面是我的代码:

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

Exception occurs at code line:

异常发生在代码行:

Workbook wb = new XSSFWorkbook(is);

Here is POI jar including:

这是 POI 罐子,包括:

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

Can any guys give me guidance? An example showing how to read a complete Excel 2007 document will be appreciated. Thanks in advance!

有大佬可以指导一下吗?展示如何阅读完整的 Excel 2007 文档的示例将不胜感激。提前致谢!

回答by David Bejar

I assume that you have recheck that your original file is indeed in Office 2007+XML format, right?

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

Edit:

编辑:

Then, if you are sure the format is ok, and it works for you using the WorkbookFactory.create, you can find the answer in the code of such method:

然后,如果您确定格式没问题,并且它适用于您使用 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");
    }

This is the bit that you were missing: new XSSFWorkbook(OPCPackage.open(inp))

这是你遗漏的一点: new XSSFWorkbook(OPCPackage.open(inp))