程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> 關於PHP編程 >> POI 讀取EXCEL實現程序

POI 讀取EXCEL實現程序

編輯:關於PHP編程

 代碼如下 復制代碼

 

/*
  * 使用POI讀取EXCEL文件
  */
 import java.io.File;
 import java.io.FileInputStream;
 import java.util.ArrayList;
 
 import org.apache.poi.hssf.usermodel.HSSFCell;
 import org.apache.poi.hssf.usermodel.HSSFRow;
 import org.apache.poi.hssf.usermodel.HSSFSheet;
 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
 
 /**
  *
  * @author Hanbin
  */
 public class ReadExcel {
 
     /**
      * @param args the command line arguments
      */
     public static void main(String[] args)throws Exception {
         read("d:demo.xls");
     }
    
     public static ArrayList read(String fileName){
         ArrayList list = new ArrayList();
         String sql = "";
         try{
             File f = new File(fileName);
             FileInputStream fis = new FileInputStream(f);
             HSSFWorkbook wbs = new HSSFWorkbook(fis);
             HSSFSheet childSheet = wbs.getSheetAt(0);
             System.out.println("行數:" + childSheet.getLastRowNum());
             for(int i = 4;i<childSheet.getLastRowNum();i++){
                 HSSFRow row = childSheet.getRow(i);
                 System.out.println("列數:" + row.getPhysicalNumberOfCells());
                 if(null != row){
                     for(int k=1;k<row.getPhysicalNumberOfCells();k++){
                         HSSFCell cell;
                         cell = row.getCell((short)k);
                        // System.out.print(getStringCellValue(cell) + "t");
                         list.add(getStringCellValue(cell) + "t");
                     }
                 }
             }
         }catch(Exception e){
             e.printStackTrace();
         }
         return list;
     }
     /**
      * 獲取單元格數據內容為字符串類型的數據
      *
      * @param cell Excel單元格
      * @return String 單元格數據內容
      */
     private static String getStringCellValue(HSSFCell cell) {
         String strCell = "";
         switch (cell.getCellType()) {
         case HSSFCell.CELL_TYPE_STRING:
             strCell = cell.getStringCellValue();
             break;
         case HSSFCell.CELL_TYPE_NUMERIC:
             strCell = String.valueOf(cell.getNumericCellValue());
             break;
         case HSSFCell.CELL_TYPE_BOOLEAN:
             strCell = String.valueOf(cell.getBooleanCellValue());
             break;
         case HSSFCell.CELL_TYPE_BLANK:
             strCell = "";
             break;
         default:
             strCell = "";
             break;
         }
         if (strCell.equals("") || strCell == null) {
             return "";
         }
         if (cell == null) {
             return "";
         }
         return strCell;
     }
 }


  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved