【问题标题】:Laravel excel export how to export conditional data?Laravel excel导出如何导出条件数据?
【发布时间】:2020-10-11 02:02:48
【问题描述】:

我正在尝试从我的表中导出部分数据而不是所有数据,我正在使用 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/ReportExport.php

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

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

【问题讨论】:

    标签: laravel laravel-7.x


    【解决方案1】:

    你可以这样做。

    第 1 步:在您的控制器中

    报表导出类中绑定$request。在调用 export excel 的方法中添加代码。

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

    第 2 步:

    protected $request;
    public function __construct($request)
    {
        $this->request = $request;
    }
    
    public function collection()
     {
    
      $request = $this->request  ;  
      return User::where('customer_id',$request->cId)->get();
     }
    

    【讨论】:

      【解决方案2】:

      您可以使用包提供的 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

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

      【讨论】:

        猜你喜欢
        • 2019-09-21
        • 1970-01-01
        • 2021-09-15
        • 2015-11-24
        • 1970-01-01
        • 2019-05-20
        • 1970-01-01
        • 2019-03-12
        • 1970-01-01
        相关资源
        最近更新 更多