如何用两张纸构建Excel并下载?

How to build Excel with two sheets and download?

我使用 Laravel Excel,这是完整代码:

<?php

namespace App\Http\Controllers;

use App\Event;
use App\Visitor;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithTitle;
use Maatwebsite\Excel\Facades\Excel;
use Exportable;
use Maatwebsite\Excel\Concerns\WithMultipleSheets;

class VisitorsSheet implements FromQuery, WithTitle
{

    private $idEvent;

    public function __construct($idEvent)
    {

        $this->idEvent = $idEvent;
    }

    public function query()
    {
        return Visitor::where("idEvent", $this->idEvent)->get();
    }

    public function title(): string
    {
        return 'Visitors';
    }
}

class EventSheet implements FromQuery, WithTitle
{
    private $idEvent;

    public function __construct($idEvent)
    {

        $this->idEvent = $idEvent;
    }

    public function query()
    {
        return Event::where("idEvent", $this->idEvent)->get();
    }

    public function title(): string
    {
        return 'Event №' . $this->idEvent;
    }
}

class ArchivingExport implements WithMultipleSheets
{

    private $eventId;

    public function __construct($eventId)
    {

        $this->eventId = $eventId;
    }

    public function sheets(): array
    {
        $sheets = [];
        $sheets[] = new EventSheet($this->eventId);
        $sheets[] = new VisitorsSheet($this->eventId);

        return $sheets;
    }
}

class ArchivingController extends Controller
{

    private $file = "settings_archive.json";

    public function __construct()
    {
        date_default_timezone_set("Asia/Tei");
    }

    private function formatName($event)
    {
        return $event->date . '_' . $event->name . '.xlsx';
    }

    public function index()
    {

        $download = [];

            try {
                $events = Event::where("status", 1)->where("archived", 0)->get();
                foreach ($events as $key => $event) {
                    $download[] = new ArchivingExport($event->idEvent); //->download($this->formatName($event));
                }

                return $download;

            } catch (Exception $e) {
                 return \json_decode([
                    'status' => false,
                    'message' =>  $e->getMessage()
                ]);

            }


       return \json_decode([
            'status' => false
        ]);

    }

}

正如您在索引方法中 class ArchivingController 中看到的那样,我尝试构建工作表:

foreach ($events as $key => $event) {
   $download[] = new ArchivingExport($event->idEvent); //->download($this->formatName($event));
}

我在$download[]中准备好了对象,但我不知道如何下载它们?它应该准备好 Excel 文件。

我尝试调用每个对象:

->download($this->formatName($event));

但是里面没有下载方法

无法使用 HTTP 协议通过同一请求同时发送多个文件。 Laravel也不支持这个。

您必须将文件打包成一个 zip 文件。

一个流行的包是Zipper