首先,將PHPExcel文件放入到vendor目錄下面:php
備註:ThinkPHP3.1的路徑是:./ThinkPHP/Extend/Vendor/;ThinkPHP3.2的路徑是:./ThinkPHP/Library/Vendor/;app
數據導出功能的實現:函數
編寫導出爲Excel的函數exportExcel:this
public function exportExcel($expTitle,$expCellName,$expTableData){
$xlsTitle = iconv('utf-8', 'gb2312', $expTitle);//文件名稱
$fileName = $_SESSION['account'].date('_YmdHis');//文件輸出的文件名
$cellNum = count($expCellName);
$dataNum = count($expTableData);excel
vendor("PHPExcel.PHPExcel");
$objPHPExcel = new PHPExcel();//ThinkPHP3.1的寫法utf-8
$objPHPExcel = new \PHPExcel();//ThinkPHP3.2的寫法,有命名空間的概念
$cellName = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ');ci
$objPHPExcel->getActiveSheet(0)->mergeCells('A1:'.$cellName[$cellNum-1].'1');//合併單元格
// $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $expTitle.' Export time:'.date('Y-m-d H:i:s'));
for($i=0;$i<$cellNum;$i++){
$objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i].'2', $expCellName[$i][1]);
}
// Miscellaneous glyphs, UTF-8
for($i=0;$i<$dataNum;$i++){
for($j=0;$j<$cellNum;$j++){
$objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j].($i+3), $expTableData[$i][$expCellName[$j][0]]);
}
}rem
header('pragma:public');
header('Content-type:application/vnd.ms-excel;charset=utf-8;name="'.$xlsTitle.'.xls"');
header("Content-Disposition:attachment;filename=$fileName.xls");//attachment新窗口打印inline本窗口打印
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');//ThinkPHP3.1的寫法get
$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');//ThinkPHP3.2的寫法,有命名空間的概念
$objWriter->save('php://output');
exit;
}it
3.讀取數據,調用數據調用數據導出函數exportExcel:
function expUser(){//導出Excel
$xlsName = "User";
$xlsCell = array( //設置字段名和列名的映射
array('id','帳號序列'),
array('truename','名字'),
array('sex','性別'),
array('res_id','院系'),
array('sp_id','專業'),
array('class','班級'),
array('year','畢業時間'),
array('city','所在地'),
array('company','單位'),
array('zhicheng','職稱'),
array('zhiwu','職務'),
array('jibie','級別'),
array('tel','電話'),
array('qq','qq'),
array('email','郵箱'),
array('honor','榮譽'),
array('remark','備註')
);
$xlsModel = M('Member');
$xlsData = $xlsModel->Field('id,truename,sex,res_id,sp_id,class,year,city,company,zhicheng,zhiwu,jibie,tel,qq,email,honor,remark')->select();
//將sex字段中1和0分貝裝換爲「男」和「女」
foreach ($xlsData as $k => $v) { $xlsData[$k]['sex']=$v['sex']==1?'男':'女'; } $this->exportExcel($xlsName,$xlsCell,$xlsData); }