企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
``` <?php namespace app\admin\controller; use app\BaseController; class Export extends BaseController { public function download() { $enToCn = [ 'door_num' => '(原)门牌号', 'name' => '客户姓名', 'id_card' => '身份证号', 'phone' => '客户电话', 'type' => '用水户类型', 'waterworks' => '所属水厂', 'grid' => '所属网格', 'recorder' => '添加人员', 'township' => '乡镇/区', 'village' => '村庄', 'site' => '水表位置(经纬度)', 'ton' => '水表吨数', 'address' => '详细地址', 'pay_num' => '缴费账号', 'check_text' => '审核状态', 'create_time' => '创建时间', ]; //此数组的顺序就是Excel表格展示的顺序 key对应的是数据库字段名 value对应的是Excel的表头 $cnToEn = array_flip($enToCn); $intToCn = array_keys($cnToEn); $intToEn = array_keys($enToCn); $time = input('time/s', ''); $startTime = null; $endTime = null; if($time) { $startTime = explode(' - ', $time)[0]; $endTime = explode(' - ', $time)[1]; } //为防止一次性导出全表数据量过大而导出失败,加上一个时间段的筛选 $data = \app\admin\model\Payform::order('id') ->append(['site','check_text']) ->where(function ($query) use ($startTime,$endTime){ if ($startTime&&$endTime) { $query->whereBetweenTime('create_time', $startTime, $endTime); } }) ->select() ->toArray(); $name = "用水户信息统计表(导出)"; $excel = new \PHPExcel(); iconv('UTF-8', 'gb2312', $name); //针对中文名转码 $excel->setActiveSheetIndex(0); $sheel = $excel->getActiveSheet(); $sheel->setTitle($name); //设置表名 $sheel->getDefaultRowDimension()->setRowHeight(14.25);//设置默认行高 $sheel->getDefaultColumnDimension()->setWidth(18);//设置默认列宽 $letterArr = ['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']; foreach ($intToEn as $k => $v) { $sheel->setCellValue($letterArr[$k] . 1, $enToCn[$v]); } // 写入内容 for($i=0; $i<count($data); $i++){ $j = $i+2; foreach ($intToEn as $k => $v) { $sheel->setCellValue($letterArr[$k] . $j, $data[$i][$v]."\t"); } } header('Content-Type: application/vnd.ms-excel'); header('Content-Disposition: attachment;filename='.$name.'.xlsx'); header('Cache-Control: max-age=0'); $objWriter = \PHPExcel_IOFactory::createWriter($excel, 'Excel2007'); $objWriter->save('php://output'); exit; } } ``` 注意:需要安装php生成excel扩展   composer require phpoffice/phpexcel 注意:Excel表头用的数组$letterArr = \['A','B','C','D','E','F','G','H','I',....\];可以使用下面方法生成 ``` function excelHead($columns) { $array = []; $n = 0; for ($i = 'A'; $i <= 'Z'; $i++) { if ($n<$columns) array_push($array, $i); $n++; } return $array; } ```