php_excel导出

1.下载PHPExcel工具

2.解压后放置位置:ThinkPHP\Extend\Vendor\PHPExcel\PHPExcel.php。

3.Common.php代码

public function exportExcel($expTitle,$expCellName,$expTableData){
$xlsTitle = iconv('utf-8', 'gb2312', $expTitle);//文件名称
$fileName = '注册码信息'.date('_YmdHis');//or $xlsTitle 文件名称可根据自己情况设定
$cellNum = count($expCellName);
$dataNum = count($expTableData);
vendor("PHPExcel.PHPExcel");

$objPHPExcel = new PHPExcel();
$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');

$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]]);
}
}

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');
$objWriter->save('php://output');
exit;
}

 

4.Action控制器调用代码

// excel导出

public function excel() {
$xlsName = "pollCode";
$xlsCell = array(
array('code_id','序号'),
array('code_number','注册码编号'),
array('user_phone','联系方式'),
array('user_card','身份证号码'),
);
$xlsModel = M('alliance_user_poll');
$xlsData = $xlsModel->Field('code_id,code_number,user_phone,user_card')->select();
foreach ($xlsData as $k => $v)
{
$xlsData[$k]['user_phone']=$v['user_phone']?$v['user_phone']:'暂无';
$xlsData[$k]['user_card']=$v['user_card']?$v['user_card']:'暂无';
}
$this->exportExcel($xlsName,$xlsCell,$xlsData);
}

 

原文:https://blog.csdn.net/s371795639/article/details/78779570 

posted @ 2019-08-05 17:56  study_php_java_C++  阅读(104)  评论(0编辑  收藏  举报