对Spreadsheet方法封装
@param array $arr 该数组必须为键值对,键是表格单元,值是单元格的值
@param array $data 该数组如果为一维数组,则填写一行,如果为二维数组,则多行数据
@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());