Laravel Excel 3.0 / 3.1导出foreach

时间:2019-01-28 07:14:30

标签: vue.js maatwebsite-excel

这是我的代码

class ReportController extends Controller{
    return (new Report)->download('report.xlsx', \Maatwebsite\Excel\Excel::XLSX);
}

class Report implements FromQuery {
    use Exportable;
    public function query(){
        return User::query();
    }    
}

将Excel导出到我的计算机是工作,但是如果我想在每一行中添加或检查一些值,我不知道该怎么做?

1 个答案:

答案 0 :(得分:0)

您需要做的是:

创建一个课程ExportReport.php

<?php

namespace NeonMobile\Exports;


class ExportReport implements WithMultipleSheets
{
    use Exportable; 

    public function __construct($data = [])
    {
        $this->myRepo = \App::make(ReportRepositoryInterface::class);
    }

    /**
     * @return array
     */
    public function sheets(): array
    {
        $reportData= $this->myRepo->myFunctionToGetData();
        $sheets[] = new ExportMultipleSheets([
            'collection' => collect($reportData),
            'title'      => 'export_invoice',
            'cells'      => ['A1:G1'],
        ]);

        return $sheets;
    }
}

另一个常见的类ExportMultipleSheets.php

<?php

namespace NeonMobile\Exports;

use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Concerns\WithTitle;
use Maatwebsite\Excel\Events\AfterSheet;

class ExportMultipleSheets implements FromCollection, WithTitle, ShouldAutoSize, WithEvents
{
    private $title;
    private $collection;
    private $cells;

    public function __construct($data = [])
    {
        $this->title = $data['title'];
        $this->collection = $data['collection'];
        $this->cells = $data['cells'];
    }

    /**
     * @return Collection
     */
    public function collection()
    {
        return $this->collection;
    }

    /**
     * @return string
     */
    public function title(): string
    {
        return $this->title;
    }
}

现在只需拨打电话

class ReportController extends Controller{
    return (new ReportExport)->download('report.xlsx', \Maatwebsite\Excel\Excel::XLSX);
}