方法一
public function xlsx($lists) { //生成文件名 $date = date("Y-m-d_H:i:s", time()); $fileName = "file_" . $date . ".xlsx"; //头部标题 $xlsx_header = ['手机号', '姓名']; ob_get_clean(); ob_start(); echo implode("\t", $xlsx_header),"\n"; $num = 0; foreach ($lists as $key => $value) { $data = []; $data[] = $value['phone']; $data[] = $value['name']; echo implode("\t", $data),"\n"; } header('Content-Disposition: attachment; filename='.$fileName); header('Accept-Ranges:bytes'); header('Content-Length:' . ob_get_length()); header('Content-Type:application/vnd.ms-excel'); ob_end_flush(); }
方法二 PHPExcel
public function xlsx($title) { $header_arr =['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']; $objPHPExcel = new PHPExcel();//实例化一个要保存的phpExcel对象 $objPHPExcel->setActiveSheetIndex(0); //在激活的工作区写入数据 (数组写入数据演示) $startRow = 1; //我这个只写入了一行 亲亲要是多行 记得 $startRow++ foreach ($title as $k=>$v) { $objPHPExcel->getActiveSheet()->setCellValue($header_arr[$k].$startRow,$v); } header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); header('Content-Disposition: attachment;filename="模板.xlsx"'); header('Cache-Control: max-age=0'); $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007'); $objWriter->save('php://output'); exit; }