1. 下载PHPExcel 文件到本地
2. 引入PHPExcel 文件 到后台文件中
3. 导出excel 文件 ,运用下列导出方法
public function actionExport(){
$query = Member::find();
$list = $query->where(['status'=>1])->orderBy('id DESC')->asArray()->all();
if(!empty($list)){
foreach ($list as $k=>$item){
$list[$k]['status'] = ($item['status']==1)?'正常':'禁用';
}
}
$headers = [
'A'=>['key'=>'id','label'=>'ID','width'=>10],
"B"=>['key'=>'username','label'=>'账号','width'=>30],
"C"=>['key'=>'nickname','label'=>'昵称','width'=>30],
"D"=>['key'=>"mobile",'label'=>"手机",'width'=>30],
"E"=>['key'=>'status','label'=>'状态','width'=>20],
"F"=>['key'=>'createTime','label'=>'注册时间','width'=>20],
];
$filename = '会员列表-'.date("Y年m月j日");
$this->format_array2excel($list,$filename,$headers);
Yii::$app->end();
}
/**
********************************************************
* 函数名: format_array2excel
* 参数:
* @param $data 导出的数据
* @param string $filename 导出的文件名
* @param $header 在全局变量 $pramas 中必须定义 excel_'.$header.'_export相应的数组作为导出表头
* 'excel_user_export' => [
* 'A'=>['key'=>'user_realname','label'=>'姓名'],
* "B"=>['key'=>'user_name','label'=>'帐号'],
* "C"=>['key'=>"user_dept",'label'=>"部门"],
* "D"=>['key'=>'grade_id','label'=>'职位']
* ],
* 函数描述:把数组导出到Excel
*******************************************************
*/
function format_array2excel($data,$filename='Excel',$header){
$objPHPExcel = new PHPExcel();
/*以下是一些设置 ,什么作者 标题啊之类的*/
$objPHPExcel->getProperties()->setCreator("wufeng")
->setLastModifiedBy("wufeng")
->setTitle("用户导出")
->setSubject("数据EXCEL导出")
->setDescription("备份数据")
->setKeywords("excel")
->setCategory("数据导出");
/*以下就是对处理Excel里的数据, 横着取数据,主要是这一步,其他基本都不要改*/
foreach ($header as $k => $v ){
//Excel的第A列,uid是你查出数组的键值,下面以此类推
$objPHPExcel->getActiveSheet()->getColumnDimension($k)->setWidth($v['width']);
// $objPHPExcel->getActiveSheet()->getColumnDimension($k)->setAutoSize(true); //自动适应宽度
$objPHPExcel->setActiveSheetIndex(0)->setCellValue($k.'1', $v['label']);
}
foreach($data as $k => $v){
$num= $k+2;
foreach ($header as $kk => $vv ) {
//Excel的第A列,uid是你查出数组的键值,下面以此类推
$objPHPExcel->setActiveSheetIndex()->setCellValue($kk . $num, $v[$vv['key']]);
}
}
$objPHPExcel->getActiveSheet()->setTitle('会员列表');
$objPHPExcel->setActiveSheetIndex(0);
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'.$filename.'.xls"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
exit;
}
PHPExcel 百度云盘下载地址: 链接:https://pan.baidu.com/s/1CYStRJv8kG6Pf1k2g0Xi2g 提取码:4zbe