Apache POI 是用Java編寫的免費(fèi)開源的跨平臺(tái)的 Java API,Apache POI提供API給Java程式對(duì)Microsoft Office格式檔案讀和寫的功能。
項(xiàng)目下載頁(yè):http://poi.apache.org/download.html
Apache POI 是創(chuàng)建和維護(hù)操作各種符合Office Open XML(OOXML)標(biāo)準(zhǔn)和微軟的OLE 2復(fù)合文檔格式(OLE2)的Java API。用它可以使用Java讀取和創(chuàng)建,修改MS Excel文件.而且,還可以使用Java讀取和創(chuàng)建MS Word和MSPowerPoint文件。Apache POI 提供Java操作Excel解決方案。
讀取Excel文檔示例
我們使用POI中的HSSFWorkbook來讀取Excel數(shù)據(jù)。
public void test(File file) throws IOException { InputStream inp = new FileInputStream(file); HSSFWorkbook workbook = new HSSFWorkbook(inp); // workbook...遍歷操作 } 上邊代碼,讀取Excel2003(xls)的文件沒問題,但是一旦讀取的是Excel2007(xlsx)的文件,就會(huì)報(bào)異常:“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來讀取,如下:
public void test(File file) throws IOException { InputStream inp = new FileInputStream(file); XSSFWorkbook workbook = new XSSFWorkbook(inp); // workbook...遍歷操作 } 注意:XSSFWorkbook需要額外導(dǎo)入poi-ooxml-3.9-sources.jar和poi-ooxml-schemas-3.9.jar。
這樣,Excel2007的導(dǎo)入沒問題了,但是導(dǎo)入Excel2003又報(bào)異常。
所以,在導(dǎo)入Excel的時(shí)候,盡量能判斷導(dǎo)入Excel的版本,調(diào)用不同的方法。
我想到過使用文件后綴名來判斷類型,但是如果有人將xlsx的后綴改為xls時(shí),如果使用xlsx的函數(shù)來讀取,結(jié)果是報(bào)錯(cuò);雖然后綴名對(duì)了,但是文件內(nèi)容編碼等都不對(duì)。
最后,推薦使用poi-ooxml中的WorkbookFactory.create(inputStream)來創(chuàng)建Workbook,因?yàn)镠SSFWorkbook和XSSFWorkbook都實(shí)現(xiàn)了Workbook接口。代碼如下:
Workbook wb = WorkbookFactory.create(is);
可想而知,在WorkbookFactory.create()函數(shù)中,肯定有做過對(duì)文件類型的判斷,一起來看一下源碼是如何判斷的:
/** * 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"); } 可以看到,有根據(jù)文件類型來分別創(chuàng)建合適的Workbook對(duì)象。是根據(jù)文件的頭部信息去比對(duì)進(jìn)行判斷的,此時(shí),就算改了后綴名,還是一樣通不過。
新聞熱點(diǎn)
疑難解答
圖片精選