码迷,mamicode.com
首页 > 编程语言 > 详细

java读写excel之POI篇—003

时间:2015-09-22 11:37:16      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:

  1. 使用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();
        }
    }


java读写excel之POI篇—003

标签:

原文地址:http://my.oschina.net/u/233752/blog/509483

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!