LoginSignup
5
5

More than 3 years have passed since last update.

Laravel Excel で .xlsx ファイル出力時にデフォルトのフォントを変更する方法

Posted at

Laravel Excel https://laravel-excel.com/ を使って、 .xlsx ファイルを出力する際にファイル全体のデフォルトのフォント変更する方法。

なお、 Laravel Excel のバージョンは 3.1 です。

結論: registerEvents() を使って、 $event->sheet->getDelegate()->getParent()->getDefaultStyle()->getFont()->setName('MS Pゴシック'); とかする

書いたとおりなのですが、 registerEvents() を使って、 $event->sheet->getDelegate()->getParent()->getDefaultStyle()->getFont()->setName('MS Pゴシック'); などとします。

どうやるのか

このチュートリアルに習って、 UsersExport を生成すると以下のファイルが生成されます。

app/Exports/UserExport.php

で、そのファイルの中は、以下のようになっているはずです。

app/Exports/UserExport.php
<?php

namespace App\Exports;

use App\User;
use Maatwebsite\Excel\Concerns\FromCollection;

class UsersExport implements FromCollection
{
    /**
    * @return \Illuminate\Support\Collection
    */
    public function collection()
    {
        return User::all();
    }
}

このクラスに Maatwebsite\Excel\Concerns\WithEvents を implements して、要求される public function registerEvents(): array; を実装します。

https://docs.laravel-excel.com/3.1/architecture/#lifecyclehttps://docs.laravel-excel.com/3.1/exports/extending.html#events を参照のこと。

app/Exports/UserExport.php
<?php

namespace App\Exports;

use App\User;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithEvents;

class UsersExport implements FromCollection, WithEvents
{
    /**
    * @return \Illuminate\Support\Collection
    */
    public function collection()
    {
        return User::all();
    }

    public function registerEvents(): array
    {
        return [
            AfterSheet::class => function (AfterSheet $event) {
                $event->sheet->getDelegate()->getParent()->getDefaultStyle()->getFont()->setName('MS Pゴシック');
            },
        ];
    }
}

で、上記のように、 PhpSpreadsheet のインスタンスを引っ張り出してきて、 最終的に setName(); します。

フォントサイズを変更したいときは、同様に setSize(); です。

PhpSpreadsheet で設定できるやつは、この方法で設定できるはず。 https://phpspreadsheet.readthedocs.io/en/latest/

5
5
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
5
5