使用WorkbookFactory打开Workbook
@Test public void openWorkbookByWorkbookFactory(){ FileInputStream fileInputStream = null; Workbook workbook = null; try { fileInputStream = new FileInputStream("D:\\test.xls"); workbook = WorkbookFactory.create(fileInputStream); //获取第一个sheet Name System.out.println(workbook.getSheetName(0)); //获取sheet总数 System.out.println(workbook.getNumberOfSheets()); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (InvalidFormatException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { fileInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } }
二,使用POIFSFileSystem打开Workbook
@Test public void openWorkbookByPOIFSFileSystem(){ FileInputStream fileInputStream = null; Workbook workbook = null; try { fileInputStream = new FileInputStream("D:\\test.xls"); POIFSFileSystem poifsFileSystem = new POIFSFileSystem(fileInputStream); workbook = new HSSFWorkbook(poifsFileSystem); //制定sheet Name还回sheet index System.out.println(workbook.getSheetIndex("三")); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { fileInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } }
三,打开加密的Workbook(读加密)
@Test public void operWorkbookOfSN(){ try { FileInputStream fileInputStream = new FileInputStream("D:\\test.xls"); BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream); POIFSFileSystem poifsFileSystem = new POIFSFileSystem(bufferedInputStream); Biff8EncryptionKey.setCurrentUserPassword("password"); HSSFWorkbook hssfWorkbook = new HSSFWorkbook(poifsFileSystem); System.out.println("====================EncryptedWorkbook===================="); System.out.println("Number of Sheets:" + hssfWorkbook.getNumberOfSheets()); System.out.println("Sheet0's name:" + hssfWorkbook.getSheetName(0)); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }