输出Xlsx到浏览器下载后,打开损坏

liyume

问题描述

环境:
PHP8.2
phpoffice/phpspreadsheet:2.0
这里写问题具体描述
截图
代码如下:
/**

  • 对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());
    }

    }

453 0 0
0个回答

×
🔝