当前位置: 首页 > 工具软件 > LaravelS > 使用案例 >

laravel-admin 使用laravels时,excel导出异常的问题

公孙胡媚
2023-12-01

预处理

新建自定义异常类

<?php
namespace App\Exceptions;
use Throwable;
use Exception;

class SwooleExitException extends Exception
{
    protected $response;
    public function __construct($response,$message = "", $code = 0, Throwable $previous = null)
    {
        $this->response = $response;
        parent::__construct($message, $code, $previous);
    }
    //获取响应内容
    public function getResponse(){
        return $this->response;
    }
}

在Handler.php中,render方法中添加代码


protected $dontReport = [
    //
    SwooleExitException::class
];
    
public function render($request, Exception $exception)
{
    
    if ($exception instanceof SwooleExitException) {
        //直接调用perpare
        return $exception->getResponse()->prepare($request);
    }
    
}

swoole_exit 为自定义的全局函数

if (!function_exists('swoole_exit')){
    function swoole_exit($response)
    {
        throw new App\Exceptions\SwooleExitException($response);
    }
}

接下来是改框架。小弟不才。没有想到其他办法。希望各位大神指点迷津。

小弟qq247552748

第一步

修改Encore\Admin\Grid\Exporters\CsvExporter.php 文件

public function export()
{
    .....
    ....

    response()->stream($response, 200, $this->getHeaders())->send();
    
    exit;
}

处理掉exit

改为

public function export()
{
    .....
    ....

   swoole_exit(response()->stream($response, 200, $this->getHeaders()));
}

第二步

Encore\Admin\Middleware\Pjax.php

跟第一步同样道理,处理掉exit方式,修改为请求返回的形式

public static function respond(Response $response)
    {
        $next = function () use ($response) {
            return $response;
        };
        swoole_exit((new static())->handle(Request::capture(), $next));
        
//        (new static())->handle(Request::capture(), $next)->send();

//        exit;
    }

第三步

Encore\Admin\Grid\Exporters\ExcelExporter

public function export()
{
//        $this->download($this->fileName)->prepare(request())->send();

        swoole_exit($this->download($this->fileName)->prepare(request()));
//        exit;
}

参考自 https://learnku.com/articles/33716

 类似资料: