- 論壇徽章:
- 0
|
PHPExcel是個很強大的類庫,以前只使用過它生成Excel文件,非常方便。
今天接到個項目要讀取Excel的文件,以前也做過Excel轉換寫入數(shù)據(jù)庫的工作,
不過相對簡單一些,是轉換成CSV格式再進行解析的。
首先下載PHPExcel類庫。http://phpexcel.codeplex.com/
包含PHPExcel類庫文件,如果不能確定文件類型的話可以使用PHPExcel_IOFactory::identify方法返回文件的類型,傳遞給該函數(shù)一個文件名就可以。
然后根據(jù)返回的文件類型創(chuàng)建該類型的讀取對象,進行文件的load。
之后就可以進行數(shù)據(jù)的讀取了, 具體代碼如下所示:
- <?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(); //行數(shù)
-
$output = array();
-
$preType = '';
-
-
$qh = $currentSheet->getCell('A4')->getValue();
-
//按照文件格式從第7行開始循環(huán)讀取數(shù)據(jù)
-
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(); //客隊
-
}
-
-
//從當前行開始往下循環(huán),取出第一個不為空的行
-
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']);
-
}
-
}
-
?>
|
|