導入:php
一、將下載好的PHPexcel文件放到libray/Org/Uti/文件夾下,將PHPEXCEL.PHP改成PHPEXCEL.class.phphtml
二、導入類文件數據庫
代碼:app
import("Org.Util.PHPExcel");
import("Org.Util.PHPExcel.Reader.Excel5");函數
三、配置post
代碼:this
$objReader = \PHPExcel_IOFactory::createReader('Excel5');//配置成2003版本,由於office版本能夠向下兼容
$objPHPExcel = $objReader->load($file,$encode='utf-8');//$file 爲解讀的excel文件url
四、解讀表格excel
代碼:code
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow(); // 取得總行數
$highestColumn = $sheet->getHighestColumn(); // 取得總列數
五、填入數據庫
代碼:
for($j=2;$j<=$highestRow;$j++)
{
$a = $objPHPExcel->getActiveSheet()->getCell("D".$j)->getValue();//白天司機姓名列
$b = $objPHPExcel->getActiveSheet()->getCell("B".$j)->getValue();//晚上司機姓名列
if(!is_null($a)){
$data['driver'] = $a;
$res = M('carcount_user')->data($data)->add();
}
}
if($res){
$this->success('填入數據庫表完成!');
}
導出:
一、
放在vendor文件夾下不用import導入,實例化便可,注意new 後要使用\
代碼:
vendor('PHPExcel');
$objExcel = new \PHPExcel();
$objWriter = \PHPExcel_IOFactory::createWriter($objExcel, 'Excel5');
二、設置表頭
$objExcel->getActiveSheet()->setCellValue('A1','司機');
三、填入數據
$count = count($driver);//$driver 爲數據庫表取出的數據
for ($i = 2; $i <= $count+1; $i++) {
$objExcel->getActiveSheet()->setCellValue('A' . $i, $driver[$i-2]['driver']);
}
四、輸出
$objExcel->setActiveSheetIndex();
header('Content-Type: applicationnd.ms-excel');
header('Content-Disposition: attachment;filename="test.xls"');
header('Cache-Control: max-age=0');
$objWriter->save('php://output');
exit;
總結:
PHPEXCEL相比reader功能多,bug少,在和TP搭配時要講文件放在vendor/(實例化便可)或者org/uti/(用import導入)下,導入時關鍵函數爲:getActiveSheet(),getCell("D".$j),getValue(),導出時關鍵函數爲getActiveSheet(),setCellValue('A1','司機')。