maatwebsite/excel使用:导出——多工作表
多工作表
为了允许导出有多个工作表,应使用 WithMultipleSheets
。 sheets()
方法需要返回一个工作表导出对象的数组。
namespace App\Exports;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\WithMultipleSheets;
class InvoicesExport implements WithMultipleSheets
{
use Exportable;
protected $year;
public function __construct(int $year)
{
$this->year = $year;
}
/**
* @return array
*/
public function sheets(): array
{
$sheets = [];
for ($month = 1; $month <= 12; $month++) {
$sheets[] = new InvoicesPerMonthSheet($this->year, $month);
}
return $sheets;
}
}
工作表类
InvoicesPerMonthSheet
可以实现 FromQuery
, FromCollection
, FromView
等关注点…
注意: WithTitle
关注点需要使用 title()
方法为每个工作表命名。
namespace App\Exports\Sheets;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithTitle;
class InvoicesPerMonthSheet implements FromQuery, WithTitle
{
private $month;
private $year;
public function __construct(int $year, int $month)
{
$this->month = $month;
$this->year = $year;
}
/**
* @return Builder
*/
public function query()
{
return Invoice
::query()
->whereYear('created_at', $this->year)
->whereMonth('created_at', $this->month);
}
/**
* @return string
*/
public function title(): string
{
return 'Month ' . $this->month;
}
}
下面的代码可以在任何类中实现,以下载今年所有发票的 xlsx 文件,其中包括 12个 工作表,每个工作表代表一年中的一个月。
public function downloadInvoices()
{
return (new InvoicesExport(2018))->download('invoices.xlsx');
}
本作品采用《CC 协议》,转载必须注明作者和本文链接