内容纲要
普通形式
private Workbook getWorkbook(String filePath, InputStream is) throws IOException {
String fileExt = this.fileExt(filePath);
return "xlsx".equals(fileExt) ? new XSSFWorkbook(is) : "xls".equals(fileExt) ? new HSSFWorkbook(is) : null;
}
推荐形式:使用工厂模式创建Workbook
// 通过文件流工厂方式来处理
Workbook workbook = WorkbookFactory.create(is);
POI源码
public static Workbook create(InputStream inp, String password) throws IOException, InvalidFormatException, EncryptedDocumentException {
InputStream is = FileMagic.prepareToCheckMagic(inp);
FileMagic fm = FileMagic.valueOf(is);
switch(fm) {
case OLE2:
NPOIFSFileSystem fs = new NPOIFSFileSystem(is);
return create(fs, password);
case OOXML:
return new XSSFWorkbook(OPCPackage.open(is));
default:
throw new InvalidFormatException("Your InputStream was neither an OLE2 stream, nor an OOXML stream");
}
}