1. 在composer.json中引入
"phpoffice/phpexcel": "1.8"
运行 composer update
安装成功后可以直接
use PHPExcel;使用
关导出的时候需要删除 FILE: /private/var/www/backend/ThinkPHP/Library/Org/Util/PHPExcel/Calculation/Functions.php LINE: 576 的break代码删除,不然会报错
public function export() { $arr = [ [ 'id' => 1, 'name' => 'wyq', 'nickname' => '心如止水', 'password' => '123456', 'phone' => '13451167651', 'init_time' => 1622632002, ], [ 'id' => 2, 'name' => 'fj', 'nickname' => 'xj', 'password' => '123456', 'phone' => '13451163651', 'init_time' => 1622632002, ] ]; //实例化 $objExcel = new \PHPExcel(); //设置文档属性 $objWriter = \PHPExcel_IOFactory::createWriter($objExcel, 'Excel2007'); //设置内容; $objActSheet = $objExcel->getActiveSheet(); $key = ord("A"); $letter = explode(',', "A,B,C,D,E,F"); //设置表头 $arrHeader = array('用户ID', '用户名', '昵称','用户密码','手机号码' ,'注册时间'); $lenth = count($arrHeader); //填充表头信息 A1:用户ID、B1:用户名、C1:昵称 for ($i = 0; $i < $lenth; $i++) { $objActSheet->setCellValue("$letter[$i]1", "$arrHeader[$i]"); }; //填充表格信息 foreach ($arr as $k => $v) { //从第二行开始 $k += 2; //表格内容 $objActSheet->setCellValue('A' . $k, $v['id']); $objActSheet->setCellValue('B' . $k, $v['name']); $objActSheet->setCellValue('C' . $k, $v['nickname']); $objActSheet->setCellValue('D' . $k, $v['password']); $objActSheet->setCellValue('E' . $k, $v['phone']); $objActSheet->setCellValue('F' . $k, date('Y-m-d H:i:s', $v['init_time'])); $width = array(20, 20, 15, 10, 10, 30, 10, 15); //设置表格的宽度 $objActSheet->getColumnDimension('A')->setWidth($width[5]); $objActSheet->getColumnDimension('B')->setWidth($width[1]); $objActSheet->getColumnDimension('C')->setWidth($width[0]); $objActSheet->getColumnDimension('D')->setWidth($width[5]); $objActSheet->getColumnDimension('E')->setWidth($width[5]); $objActSheet->getColumnDimension('F')->setWidth($width[5]); $outfile = "人员表" . time() . ".xlsx"; } //清空输出缓冲区 ob_end_clean(); //告诉浏览器强制下载 header("Content-Type: application/force-download"); //二进制文件类型 header("Content-Type: application/octet-stream"); header("Content-Type: application/download"); //设置表名 header('Content-Disposition:inline;filename="' . $outfile . '"'); header("Content-Transfer-Encoding: binary"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Pragma: no-cache"); $objWriter->save('php://output'); }