安装phpExcel
composer require "phpoffice/phpexcel": "*"
//要使用的数据
$Country_model = new Country();
$country = $Country_model->find()->asArray()->all();
//实例化
$objPHPExcel = new \PHPExcel();
$objWriter = new \PHPExcel_Writer_Excel5($objPHPExcel);
//设置表头的值还有颜色
$objPHPExcel->getActiveSheet()->setCellValue('A1', '序号');
$objPHPExcel->getActiveSheet()->getStyle('A1')->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setRGB('#ADDE79');
$objPHPExcel->getActiveSheet()->setCellValue('B1', 'code');
$objPHPExcel->getActiveSheet()->getStyle('B1')->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setRGB('#ADDE79');
$objPHPExcel->getActiveSheet()->setCellValue('C1', 'name');
$objPHPExcel->getActiveSheet()->getStyle('C1')->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setRGB('#ADDE79');
//动态生成列,从f开始,f对应的ascii为69
foreach ($country as $key => $value) {
$i=$key+2;
$objPHPExcel->getActiveSheet()->setCellValue('A'.$i, $key+1);
$objPHPExcel->getActiveSheet()->setCellValue('B'.$i, $value['code']);
$objPHPExcel->getActiveSheet()->setCellValue('C'.$i, $value['name']);
}
//下载这个表格,在浏览器输出
$file_name = '城市列表';
header("Pragma: public");
header("Expires: 0");
header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
header("Content-Type:application/force-download");
header("Content-Type:application/vnd.ms-execl");
header("Content-Type:application/octet-stream");
header("Content-Type:application/download");;
header('Content-Disposition:attachment;filename='.$file_name.'.xls');
header("Content-Transfer-Encoding:binary");
$objWriter->save('php://output');
exit; //重点是需要exit
安装php-excel
composer require --prefer-dist moonlandsoft/yii2-phpexcel "*"
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="xiazai.xlsx"');
header('Cache-Control: max-age=0');
\moonland\phpexcel\Excel::export([
'models' => Country::find()->all(),
'columns' => [
[
'header' => 'id',
'format' => 'text',
'value' => function($model) {
return $model->id;
},
],
[
'header' => 'name',
'format' => 'text',
'value' => function($model) {
return $model->name;
},
],
],