Why do I failed to read Excel 2007 using POI?

你。 提交于 2019-12-17 16:44:05

问题


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

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:

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-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!


回答1:


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

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:

   /**
     * 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))



来源:https://stackoverflow.com/questions/12593752/why-do-i-failed-to-read-excel-2007-using-poi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!