使用到的包: poi-ooxml-3.14.jar; poi-ooxml.jar;
1. 在網上查找相關文件,最多的答案就是使用 HSSFWorkbook 進行讀取:
POIFSFileSystem poifsFileSystem = new POIFSFileSystem(new FileInputStream(file)); HSSFWorkbook workbook = new HSSFWorkbook(poifsFileSystem);
結果:對xlsx文件識別不了;
2.專門針對xlsx文件找解決方案,得到用 XSSFWorkbook 進行處理;
XSSFWorkbook workbook = new XSSFWorkbook(new BufferedInputStream(stream));
結果:可以識別xlsx文件;
3.需要對文件進行判定,什么情況用 HSSFWorkbook,什么情況下用XSSFWorkbook
if(!inp.markSupported())
inp = new PushbackInputStream(inp, 8);
if(NPOIFSFileSystem.hasPOIFSHeader(IOUtils.peekFirst8Bytes(inp))){
NPOIFSFileSystem fs = new NPOIFSFileSystem(inp);
}else if(POIXMLDocument.hasOOXMLHeader(inp))
return new XSSFWorkbook(OPCPackage.open(inp));
else
throw new InvalidFormatException("你的excel版本目前poi解析不了");
ok,看似完美解決問題,但其實在WorkbookFactory里已經有了對excel 的相關操作方法
4. 借用工具類 WorkbookFactory
/**
* 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");
}
5. 終極版
Workbook workbook = WorkbookFactory.create(new FileInputStream(file));
一行代碼搞定,^_^;
