- 1
- /**
- 2 * Factory for creating the appropriate kind of Workbook
- 3 * (be it HSSFWorkbook or XSSFWorkbook), from the given input
- 4 */
- 5 public class WorkbookFactory {
- 6
- /**
- 7 * Creates an HSSFWorkbook from the given POIFSFileSystem
- 8 */
- 9 public static Workbook create(POIFSFileSystem fs) throws IOException {
- 10
- return new HSSFWorkbook(fs);
- 11
- }
- 12
- /**
- 13 * Creates an HSSFWorkbook from the given NPOIFSFileSystem
- 14 */
- 15 public static Workbook create(NPOIFSFileSystem fs) throws IOException {
- 16
- return new HSSFWorkbook(fs.getRoot(), true);
- 17
- }
- 18
- /**
- 19 * Creates an XSSFWorkbook from the given OOXML Package
- 20 */
- 21 public static Workbook create(OPCPackage pkg) throws IOException {
- 22
- return new XSSFWorkbook(pkg);
- 23
- }
- 24
- /**
- 25 * Creates the appropriate HSSFWorkbook / XSSFWorkbook from
- 26 * the given InputStream.
- 27 * Your input stream MUST either support mark/reset, or
- 28 * be wrapped as a {@link PushbackInputStream}!
- 29 */
- 30 public static Workbook create(InputStream inp) throws IOException,
- InvalidFormatException {
- 31 // If clearly doesn't do mark/reset, wrap up
- 32
- if (!inp.markSupported()) {
- 33 inp = new PushbackInputStream(inp, 8);
- 34
- }
- 35 36
- if (POIFSFileSystem.hasPOIFSHeader(inp)) {
- 37
- return new HSSFWorkbook(inp);
- 38
- }
- 39
- if (POIXMLDocument.hasOOXMLHeader(inp)) {
- 40
- return new XSSFWorkbook(OPCPackage.open(inp));
- 41
- }
- 42
- throw new IllegalArgumentException("Your InputStream was neither an OLE2 stream, nor an OOXML stream");
- 43
- }
- 44
- /**
- 45 * Creates the appropriate HSSFWorkbook / XSSFWorkbook from
- 46 * the given File, which must exist and be readable.
- 47 */
- 48 public static Workbook create(File file) throws IOException,
- InvalidFormatException {
- 49
- if (!file.exists()) {
- 50
- throw new FileNotFoundException(file.toString());
- 51
- }
- 52 53
- try {
- 54 NPOIFSFileSystem fs = new NPOIFSFileSystem(file);
- 55
- return new HSSFWorkbook(fs.getRoot(), true);
- 56
- } catch(OfficeXmlFileException e) {
- 57 OPCPackage pkg = OPCPackage.open(file);
- 58
- return new XSSFWorkbook(pkg);
- 59
- }
- 60
- }
- 61
- }
来源: http://www.bubuko.com/infodetail-1961425.html