eagle

学无止境,细节决定成败.
posts - 12, comments - 11, trackbacks - 0, articles - 2
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

poi解析excel列子

Posted on 2016-03-18 09:51 月下孤城 阅读(232) 评论(0)  编辑  收藏 所属分类: java
工作中有时会用java程序分析excel文件内容。本文介绍使用poi解析excel 2007及以上版本的方法,以备参考。

 1 /**
 2      * poi解析excel    sample
 3      * 针对2007及以上版本 使用XSSF解析
 4      * @throws EncryptedDocumentException
 5      * @throws InvalidFormatException
 6      * @throws IOException
 7      */
 8     public void parseExcel() throws EncryptedDocumentException, InvalidFormatException, IOException{
 9         InputStream is = new FileInputStream("e:\\excel.xlsx");
10         Workbook workbook = WorkbookFactory.create(is);  
11         Sheet sheet = null;
12         for (int i = 0; i < workbook.getNumberOfSheets(); i++) {// 获取每个Sheet表
13             sheet = workbook.getSheetAt(i);
14             String sheetName = sheet.getSheetName();
15             if(workbook.isSheetHidden(i)){
16                 //判断sheet页是否被隐藏
17                 System.out.println("sheet="+sheetName+", is hidden.");
18                 continue;
19             }
20             for (int j = 0; j < sheet.getPhysicalNumberOfRows(); j++) {// 获取每行
21                 if(j==0)    //第一行title,不处理
22                     continue;
23                 Row row = sheet.getRow(j);
24                 if(row == null)
25                     continue;
26                 //处理每行数据
27                 try {
28                     if(row.getZeroHeight()){
29                         //行是否被隐藏
30                         System.out.println("---Sheet表["+sheetName+"],第" + j + "行被隐藏,不处理---");
31                         continue;
32                     }
33                     int columns = row.getPhysicalNumberOfCells();
34                     for(int c=0;c<columns;c++){
35                         Cell cell = row.getCell(c);
36                         //TODO: busyness process
37                     }
38                 } catch (Exception e) {
39                     System.out.println("---Sheet表["+sheetName+"],第" + j + "行处理出错.---");
40                     e.printStackTrace();
41                     throw new RuntimeException(e);
42                 }
43                 
44                 System.out.println("---Sheet表["+sheetName+"],第" + j + "行处理完毕---");
45             }    
46         }    
47     }



---------------------
月下孤城
mail:eagle_daiqiang@sina.com

只有注册用户登录后才能发表评论。


网站导航: