我正在尝试从表中导出部分数据而不是所有数据,我正在使用 Maatwebsiteplugin https://laravel-excel.com/
我在控制器中尝试过以下代码
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 文件。
创建应用程序/导出后我能够获取所有数据
像下面这样
应用程序/导出/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');
我没有测试过代码。如果我犯了错误,请道歉。您可以参考官方文档 https://docs.laravel-excel.com/3.1/exports/from-query.html#from-query.
您还可以从文档中找到其他导出方法。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)