Laravel excel export 如何导出条件数据?

Laravel excel export how to export conditional data?

我正在尝试从我的 table 而非所有数据中导出部分数据,我正在使用 Maatwebsite plugin

我在控制器中尝试了以下代码

public function report(Request $request)
{
       
     
        $sdate  = $request->query('sdate');
        $edate  = $request->query('edate');
       
        
       
        $report = Report::whereDate('created_at', '>=', $sdate)
                                   ->whereDate('created_at', '<=', $edate)
                                   ->get();
        

        
       return Excel::download($report, 'report.xlsx');

 }

这次我正在清空 excel 文件。

创建后我能够获取所有数据app/export

喜欢下面

app/export/ReportExport.php

public function collection()
{
        return Report::all();
}

但是我怎样才能在控制器中做到这一点?或者如何将 $report 数据控制器发送到集合?

您可以使用包提供的 FromQuery 关注点。

namespace App\Exports;

use App\Report;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\Exportable;

class ReportExport implements FromQuery
{
    use Exportable;

    public function __construct($start, $end)
    {
        $this->start = $start;
        $this->end = $end;
    }

    public function query()
    {
        return Report::query()->whereDate('created_at', '>=', $this->start)
                              ->whereDate('created_at', '<=', $this->end);
    }
}

然后从你的控制器,你可以调用它

return (new ReportExport($sdate, $edate))->download('report.xlsx');

我没有测试代码。如果我犯了错误,我深表歉意。可以参考official documentation.

还有其他导出方法,您可以从文档中找到。

你可以这样做。

Step 1: in your controller

Report-Export Class 中绑定 $request。在调用 export excel.

的方法中添加代码
return Excel::download(new ReportExport($request), 'report.xlsx');

step 2:

protected $request;
public function __construct($request)
{
    $this->request = $request;
}

public function collection()
 {

  $request = $this->request  ;  
  return User::where('customer_id',$request->cId)->get();
 }