// 設置列名最多40個 $cols = array( "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", "AL", "AM", "AN", "AO", "AP", "AQ", "AR", "AS", "AT", "AU", "AV", "AW", "AX", "AY", "AZ", "BA", "BB", "BC", "BD", "BE" ); // 設置行寬 $col_width = 25; $excelpath = dirname(Yii::$app->basePath).DIRECTORY_SEPARATOR.'weixin'.DIRECTORY_SEPARATOR.'phpexcel'.DIRECTORY_SEPARATOR; include_once $excelpath . 'PHPExcel.php'; include_once $excelpath . 'PHPExcel'.DIRECTORY_SEPARATOR.'IOFactory.php'; $excel = new \PHPExcel(); //設置Excel文件元數據 $excel->getProperties()->setTitle($title)->setDescription("none"); //默認列樣式 $style = array( 'font' => array('bold' => true, 'color' => array('argb' => '00000000')), 'alignment' => array('horizontal' => \PHPExcel_Style_Alignment::HORIZONTAL_CENTER), ); //設置列寬度 foreach ($cols as $col) { $excel->getActiveSheet()->getColumnDimension($col)->setWidth($col_width); } //設置基礎表頭信息 $sheet = $excel->setActiveSheetIndex(0); foreach ($tab as $k => $v) { $sheet->setCellValue($cols[$k] . '1', $v); } // 設置內容 foreach($data as $k=>$val){ $rows = $k+2; $j = 0; foreach($val as $i=>$v){ if($i == 'GENDER' && $v ==0 ) { $v='男'; }else if($i == 'GENDER' && $v ==1){ $v='女'; } if($i == 'IDCARD') { $v="'".$v; } $sheet->setCellValue($cols[$j] . $rows, $v); if(is_numeric($v)){ $excel->getActiveSheet()->getStyle($cols[$j] . $rows)->getNumberFormat()->setFormatCode("@"); } $j++; } } $excel->getActiveSheet()->getPageSetup()->setOrientation(\PHPExcel_Worksheet_PageSetup::ORIENTATION_PORTRAIT); $excel->getActiveSheet()->getPageSetup()->setPaperSize(\PHPExcel_Worksheet_PageSetup::PAPERSIZE_A4); $objWriter = \PHPExcel_IOFactory::createWriter($excel, 'Excel2007'); $objWriter->setOffice2003Compatibility(true); header('Content-Type: application/vnd.ms-excel'); header('Content-Disposition: attachment;filename="' . $title . '.xlsx"'); header('Cache-Control: max-age=0'); $objWriter->save('php://output');