標籤:class code tar ext int http
PHPExcel是個很強大的類庫,以前只使用過它產生Excel檔案,非常方便。
今天接到個項目要讀取Excel的檔案,以前也做過Excel轉換寫入資料庫的工作,
不過相對簡單一些,是轉換成CSV格式再進行解析的。
首先下載PHPExcel類庫。http://phpexcel.codeplex.com/
包含PHPExcel類庫檔案,如果不能確定檔案類型的話可以使用PHPExcel_IOFactory::identify方法返迴文件的類型,傳遞給該函數一個檔案名稱就可以。
然後根據返回的檔案類型建立該類型的讀取對象,進行檔案的load。
之後就可以進行資料的讀取了,
具體代碼如下所示:
- <?php
- require_once(‘include/common.inc.php‘);
- require_once(ROOTPATH . ‘include/phpExcel/PHPExcel/IOFactory.php‘);
-
- $filePath = ‘./file/xls/110713.xls‘;
-
- $fileType = PHPExcel_IOFactory::identify($filePath); //檔案名稱自動判斷檔案類型
- $objReader = PHPExcel_IOFactory::createReader($fileType);
- $objPHPExcel = $objReader->load($filePath);
-
- $currentSheet = $objPHPExcel->getSheet(0); //第一個活頁簿
- $allRow = $currentSheet->getHighestRow(); //行數
- $output = array();
- $preType = ‘‘;
-
- $qh = $currentSheet->getCell(‘A4‘)->getValue();
- //按照檔案格式從第7行開始迴圈讀取資料
- for($currentRow = 7;$currentRow<=$allRow;$currentRow++){
- //判斷每一行的B列是否為有效序號,如果為空白或者小於之前的序號則結束
- $xh = (int)$currentSheet->getCell(‘B‘.$currentRow)->getValue();
- if(empty($xh))break;
-
- $tmpType = (string)$currentSheet->getCell(‘C‘.$currentRow)->getValue(); //賽事類型
- if(!empty($tmpType))$preType = $tmpType;
- $output[$xh][‘type‘] = $preType;
- $output[$xh][‘master‘] = $currentSheet->getCell(‘F‘.$currentRow)->getValue(); //主隊
- $output[$xh][‘guest‘] = $currentSheet->getCell(‘H‘.$currentRow)->getValue(); //客隊
- }
-
- //從當前行開始往下迴圈,取出第一個不為空白的行
- for( ; ; $currentRow++){
- $xh = (int)$currentSheet->getCell(‘B‘.$currentRow)->getValue();
- if(!empty($xh))break;
- }
-
- for( ; $currentRow <= $allRow; $currentRow++){
- $xh = (int)$currentSheet->getCell(‘B‘.$currentRow)->getValue();
- if(empty($xh))break;
-
- $output[$xh][‘rq‘] = $currentSheet->getCell(‘I‘.$currentRow)->getValue();
- }
- header("content-type:text/html; charset=utf-8");
-
- echo ‘期號:‘ . $qh . "\n\n";
- if(!empty($output)){
- printf("%-5s\t%-15s\t%-40s\t%-40s\t%-5s\n", ‘序號‘, ‘賽事類型‘, ‘主隊‘, ‘客隊‘, ‘讓球值‘);
- foreach($output as $key => $row){
- $format = "%-5d\t%-15s\t%-40s\t%-40s\t%-5s\n";
- printf($format, $key, $row[‘type‘], $row[‘master‘], $row[‘guest‘], $row[‘rq‘]);
- }
- }
- ?>