2012-09-26 54 views
1

當我嘗試初始化一個工作簿對象,我總是得到這個錯誤:爲什麼我未能使用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); 

異常出現在代碼行:

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文檔的示例將不勝感激。提前致謝!

回答

3

我認爲你已經重新檢查過你的原始文件確實是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))

+0

我覺得我的Excel源代碼沒有問題。 –

+0

解決。我可以通過以下代碼閱讀: File inputFile = new File(inputFileName); Workbook wb = WorkbookFactory.create(new FileInputStream(inputFile)); 即使它工作,我不知道下面和上面的代碼之間有什麼區別。 –

+0

看到我上面編輯的答案 –

相關問題