<?php // PHPExcel 需要下載 官網:http://www.codeplex.com/PHPExcel header("Content-Type: text/html; charset=utf-8"); require_once './PHPExcel.php'; require_once './PHPExcel/IOFactory.php'; require_once './PHPExcel/Reader/Excel5.php'; /** * 讀取Excel表格 * @param $filePath Excel文件路徑 * @param $field 需要保存的字段 array('id','username','password') * @param $column 讀取Excel那列 array('A','B','C') * @examlpe $filePath = '1.xls'; $field = array('id', 'username', 'password'); $column = array( 'A', 'B', 'C'); readExcel($filePath,$field,$column); */ function readExcel($filePath,$field,$column){ $objReader = PHPExcel_IOFactory::createReader('Excel5');//use excel2007 for 2007 format $objPHPExcel = $objReader->load($filePath); //$filename可以是上傳的文件,或者是指定的文件 $sheet = $objPHPExcel->getSheet(0); $highestRow = $sheet->getHighestRow(); // 取得總行數 $highestColumn = $sheet->getHighestColumn(); // 取得總列數 for($j=1;$j<=$highestRow;$j++) { $colData = array(); $count = count($column); for($i=0;$i<$count;$i++){ $colData[$field[$i]] = $objPHPExcel->getActiveSheet()->getCell($column[$i].$j)->getValue();//獲取A列的值 } $excelData[] = $colData; } return $excelData; } /** * 導出數據為excel表格 * @param $data 一個二維數組,結構如同從數據庫查出來的數組 * @param $title excel的第一行標題,一個數組,如果為空則沒有標題 * @param $filename 下載的文件名 * @examlpe exportexcel($arr,array('id','賬戶','密碼','昵稱'),'文件名!'); */ function exportexcel($data=array(),$title=array(),$filename='report'){ header("Content-type:application/octet-stream"); header("Accept-Ranges:bytes"); header("Content-type:application/vnd.ms-excel"); header("Content-Disposition:attachment;filename=".$filename.".xls"); header("Pragma: no-cache"); header("Expires: 0"); //導出xls 開始 if (!empty($title)){ foreach ($title as $k => $v) { $title[$k]=iconv("UTF-8", "GB2312",$v); } $title= implode("\t", $title); echo "$title\n"; } if (!empty($data)){ foreach($data as $key=>$val){ foreach ($val as $ck => $cv) { $data[$key][$ck]=iconv("UTF-8", "GB2312", $cv); } $data[$key]=implode("\t", $data[$key]); } echo implode("\n",$data); } } ?>