16
16

More than 3 years have passed since last update.

laravel-excel3.1 で テンプレートを読み込んで出力する

Last updated at Posted at 2019-10-26

laravel-excel3.1 で テンプレートを読み込んで出力する

Laravel開発でエクセルを扱うときの定番パッケージ「Laravel Excel」ですが、内部的にはPhpSpreadsheet を利用しているため、テンプレートとしてxlsxファイルを読み込んで出力することができます。
ただ、ドキュメントにはそのものズバリとは書かれていないため、かなーりドキュメントを読み解くことが強いられます。

https://laravel-excel.com/

ざっくりと、サンプルコード作りましたので、参考になれば。

php artisan make:export CompanyExport --model=Company

こんな感じで、雛形を出力した後、app/Exports/CompanyExport.php を以下のように編集します。

<?php

namespace App\Exports;

use App\Models\Company;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Events\BeforeExport;
use Maatwebsite\Excel\Excel;
use Maatwebsite\Excel\Files\LocalTemporaryFile;

class CompanyExport implements FromCollection, WithEvents
{
    use Exportable;

    private $template_file = null;

    /**
     * @param string $template_file
     * @return $this
     */
    public function setTemplate(string $template_file)
    {
        if (file_exists($template_file)) {
            $this->template_file = $template_file;
        }
        return $this;
    }

    /**
     * @return Collection
     */
    public function collection()
    {
        return Company::all();
    }

    /**
     * @return array
     */
    public function registerEvents(): array
    {
        return [
            BeforeExport::class => function (BeforeExport $event) {
                if (is_null($this->template_file)) {
                    return;
                }
                $event->writer->reopen(new LocalTemporaryFile($this->template_file), Excel::XLSX);
                $event->writer->getSheetByIndex(0);
                return $event->getWriter()->getSheetByIndex(0);
            },
        ];
    }
}

出力する時には、以下のように利用します。

(new CompanyExport)->setTemplate('template.xlsx')->store('output.xlsx');
16
16
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
16