工作中有時會用java程序分析excel文件內容。本文介紹使用poi解析excel 2007及以上版本的方法,以備參考。
---------------------
月下孤城
mail:eagle_daiqiang@sina.com
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 }
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