getActiveSheet(); // 列号转字母函数 $colIndexToLetter = function ($index) { $letters = ''; while ($index >= 0) { $letters = chr($index % 26 + 65) . $letters; $index = intval($index / 26) - 1; } return $letters; }; // 写入数据 foreach ($data as $rowIndex => $row) { foreach ($row as $colIndex => $value) { $cell = $colIndexToLetter($colIndex) . ($rowIndex + 1); // 例如 A1, B1... $sheet->setCellValue($cell, $value); } } // 输出到浏览器 header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); header("Content-Disposition: attachment; filename=\"{$filename}\""); header('Cache-Control: max-age=0'); $writer = new Xlsx($spreadsheet); $writer->save('php://output'); exit; } /** * 导出 CSV * @param array $data 二维数组(含表头) * @param string $filename 导出文件名 */ public static function exportCsv(array $data, string $filename = '') { if (empty($data)) { throw new \Exception('导出数据不能为空'); } $filename = $filename ?: '导出_' . date('Ymd_His') . '.csv'; header('Content-Type: text/csv'); header("Content-Disposition: attachment; filename={$filename}"); $fp = fopen('php://output', 'w'); fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF)); // 防止中文乱码 foreach ($data as $row) { fputcsv($fp, $row); } fclose($fp); exit; } }