getActiveSheet(); // 获取列数 $columnCount = count($ceshiyong_data[0]); // 添加标题到工作表中 $titles = $ceshiyong_data[0]; for ($colIndex = 0; $colIndex < $columnCount; $colIndex++) { $sheet->setCellValueByColumnAndRow($colIndex + 1, 1, $titles[$colIndex]); } // 添加数据到工作表中 $data = array_slice($ceshiyong_data, 1); foreach ($data as $rowIndex => $rowData) { for ($colIndex = 0; $colIndex < $columnCount; $colIndex++) { $sheet->setCellValueByColumnAndRow($colIndex + 1, $rowIndex + 2, $rowData[$colIndex]); } } // 设置表头样式 $headerStyle = [ 'font' => [ 'bold' => true, ], 'fill' => [ 'fillType' => Fill::FILL_SOLID, 'startColor' => [ 'argb' => 'FFFFC000', // 橙色 ], ], 'alignment' => [ 'horizontal' => Alignment::HORIZONTAL_CENTER, ], 'borders' => [ 'allBorders' => [ 'borderStyle' => Border::BORDER_THIN, ], ], ]; $sheet->getStyle('A1:' . $this->getExcelColumnName($columnCount) . '1')->applyFromArray($headerStyle); // 设置所有内容居中 $allContentStyle = [ 'alignment' => [ 'horizontal' => Alignment::HORIZONTAL_CENTER, ], 'borders' => [ 'allBorders' => [ 'borderStyle' => Border::BORDER_THIN, ], ], ]; $sheet->getStyle('A1:' . $this->getExcelColumnName($columnCount) . (count($ceshiyong_data) + 1))->applyFromArray($allContentStyle); // 设置斑马纹效果 $rowCount = count($ceshiyong_data) - 1; // 数据行数 for ($rowIndex = 1; $rowIndex <= $rowCount; $rowIndex++) { $row = $rowIndex + 1; // 数据行从第二行开始 $rowStyle = [ 'fill' => [ 'fillType' => Fill::FILL_SOLID, 'startColor' => [ 'argb' => ($rowIndex % 2 == 0) ? 'FFDDDDDD' : 'FFFFFFFF', // 偶数行浅灰色,奇数行白色 ], ], ]; $sheet->getStyle('A' . $row . ':' . $this->getExcelColumnName($columnCount) . $row)->applyFromArray($rowStyle); } // 设置响应头以触发文件下载 header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); header('Content-Disposition: attachment;filename="' . $filename . '"'); header('Cache-Control: max-age=0'); // 保存并输出 Excel 文件 $writer = new Xlsx($spreadsheet); $writer->save('php://output'); exit; } /** * 获取 Excel 列名 * * @param int $index 列索引(从1开始) * @return string Excel 列名 */ private function getExcelColumnName($index) { $columnName = ''; while ($index > 0) { $remainder = ($index - 1) % 26; $columnName = chr(65 + $remainder) . $columnName; $index = intval(($index - 1) / 26); } return $columnName; } }