环境:
PHP8.2
phpoffice/phpspreadsheet:2.0
这里写问题具体描述
代码如下:
/**
@param string $name 下载Excel的文件名,可忽略
*/
public static function downloadExcel(array $arr,array $data,$name=""){
//文件名处置
try {
if (empty($name)){
$name = date("YmdHis");
}
//内容设置
$preadsheet = new Spreadsheet();
$sheet = $preadsheet->getActiveSheet();
foreach($arr as $k=>$v){
$sheet->setCellValue($k,$v);
}
$sheet->fromArray($data,null,"A2");
//样式设置
$sheet->getDefaultColumnDimension()->setWidth(12);
//设置下载与后缀
$suffix = "xlsx";
$filename = $name.".".$suffix;
$writer = new Xlsx($preadsheet);
$response = response();
ob_start();
try {
$writer->save('php://output');
$c = ob_get_contents();
$response->withHeaders([
'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'Content-Disposition' => 'attachment;filename="'.$filename,
'Cache-Control' => 'max-age=0',
])->withBody($c);
} catch (\Throwable $e){
Log::error("生成文档出错,错误信息:".$e->getMessage());
// var_dump("生成文档出错,错误信息:".$e->getMessage());
} finally {
ob_end_clean();
}
return $response;
} catch (\Throwable $e){
Log::error("生成文档出错,错误信息:".$e->getMessage());
}
}