Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

java - Why do I failed to read Excel 2007 using POI?

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

Just Browsing Browsing

[4] html - How to create even cell spacing within a

1.4m articles

1.4m replys

5 comments

57.0k users

...