フリーランス 技術調査ブログ

フリーランス/エンジニア Ruby Python Nodejs Vuejs React Dockerなどの調査技術調査の備忘録

Laravel Excelでエクスポートを実装してみる

はじめに

  • 前回、Laravel Excelをインストールしたので、今回は実際に利用してみる

設定

  • config/app.phpに下記の記述を行う
'providers' => [
    Maatwebsite\Excel\ExcelServiceProvider::class,
]

'aliases' => [
    ...
    'Excel' => Maatwebsite\Excel\Facades\Excel::class,
]
  • 下記のコマンドを実行して構成ファイルを作成する。
  • 実行するとconfig/excel.phpファイルが作成される
php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider"

実装

  • app/ Exportsフォルダにエクスポートクラスを作成する。
  • make:exportコマンドを使用して作成する。
$ php artisan make:export UsersExport --model=User
  • 下記のファイルが作成される。下記のファイルをコントローラーから呼び出す。
<?php

namespace App\Exports;

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

class UsersExport implements FromCollection
{
    /**
    * @return \Illuminate\Support\Collection
    */
    public function collection()
    {
        return User::all();
    }
}
  • コントローラーの実装
use App\Exports\UsersExport;
use Maatwebsite\Excel\Facades\Excel;
use Maatwebsite\Excel\Excel as ExcelType;

class TestController extends Controller
{
    public function export() 
    {
        return Excel::download(new UsersExport(), 'example.xlsx', ExcelType::XLSX);
    }
  • 実行すると下記のエラーが発生する
Unable to resolve NULL driver for [Maatwebsite\Excel\Transactions\TransactionManager].
  • 下記のコマンドを実行すると解決することができる
php artisan config:clear

stackoverflow.com

  • 下記のエラーが発生した場合、下記のgithubのissueページを参考にしてみてください。
The filename and the fallback cannot contain the "/" and "\" characters.

github.com

実行結果

f:id:PX-WING:20201106005405p:plain