Apache POI 创建不同的workbook对象

内容纲要

普通形式

  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");
        }
    }

Leave a Comment

您的电子邮箱地址不会被公开。 必填项已用*标注

close
arrow_upward