原文地址:https://blog.csdn.net/it_wangxiangpan/article/details/42778167
我們使用POI中的HSSFWorkbook來讀取Excel數據。

public void test(File file) throws IOException { InputStream inp = new FileInputStream(file); HSSFWorkbook workbook = new HSSFWorkbook(inp); // workbook...遍歷操作 }
上邊代碼,讀取Excel2003(xls)的文件沒問題,但是一旦讀取的是Excel2007(xlsx)的文件,就會報異常:
“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)”
查閱了資料,Excel2007版本的Excel文件需要使用XSSFWorkbook來讀取,如下:

1 2 public void test(File file) throws IOException { 3 4 InputStream inp = new FileInputStream(file); 5 6 XSSFWorkbook workbook = new XSSFWorkbook(inp); 7 8 9 // workbook...遍歷操作 10 11 }
注意:XSSFWorkbook需要額外導入poi-ooxml-3.9-sources.jar和poi-ooxml-schemas-3.9.jar。
這樣,Excel2007的導入沒問題了,但是導入Excel2003又報異常。
所以,在導入Excel的時候,盡量能判斷導入Excel的版本,調用不同的方法。
我想到過使用文件后綴名來判斷類型,但是如果有人將xlsx的后綴改為xls時,如果使用xlsx的函數來讀取,結果是報錯;雖然后綴名對了,但是文件內容編碼等都不對。
最后,推薦使用poi-ooxml中的WorkbookFactory.create(inputStream)來創建Workbook,因為HSSFWorkbook和XSSFWorkbook都實現了Workbook接口。代碼如下:
Workbook wb = WorkbookFactory.create(is);
可想而知,在WorkbookFactory.create()函數中,肯定有做過對文件類型的判斷,一起來看一下源碼是如何判斷的:

1 /** 2 3 * Creates the appropriate HSSFWorkbook / XSSFWorkbook from 4 5 * the given InputStream. 6 7 * Your input stream MUST either support mark/reset, or 8 9 * be wrapped as a {@link PushbackInputStream}! 10 11 */ 12 13 public static Workbook create(InputStream inp) throws IOException, InvalidFormatException { 14 15 // If clearly doesn't do mark/reset, wrap up 16 17 if(! inp.markSupported()) { 18 19 inp = new PushbackInputStream(inp, 8); 20 21 } 22 23 24 25 if(POIFSFileSystem.hasPOIFSHeader(inp)) { 26 27 return new HSSFWorkbook(inp); 28 29 } 30 31 if(POIXMLDocument.hasOOXMLHeader(inp)) { 32 33 return new XSSFWorkbook(OPCPackage.open(inp)); 34 35 } 36 37 throw new IllegalArgumentException("Your InputStream was neither an OLE2 stream, nor an OOXML stream"); 38 39 }
可以看到,有根據文件類型來分別創建合適的Workbook對象。是根據文件的頭部信息去比對進行判斷的,此時,就算改了后綴名,還是一樣通不過。