今回Laravelにmaatwebsite/excelをインストールし、エクセルを出力する方法をご紹介します。
maatwebsite/excelインストール環境
Laravelのバージョンは6.18.39で、さくらのレンタルサーバー(スタンダードプラン)にインストールしました。
maatwebsite/excelのインストール
maatwebsite/excelインストールコマンドを実行(さくらのレンタルサーバー)
Laravelが稼働しているディレクトリに移動(cd)し、以下のコマンドを実行します。composer.pharの場所を指定する必要があります。
php /home/{サーバー契約ユーザー名}/www/{laravel稼働ディレクトリ}/composer.phar require maatwebsite/excel
maatwebsite/excelインストールコマンドを実行(composerコマンドが実行可能な環境)
他の参考サイトだと以下を実行すればよいとありましたが、私のさくらのレンタルサーバー環境だとcomposerコマンドが見つからないと出力されたので上記コマンドを実行しました。
composer require maatwebsite/excel
maatwebsite/excelインストールコマンド実行でエラーが出た場合
Laravel6.18.39でmaatwebsite/excelインストールコマンドを実行すると、
~
Problem1
~
Problem2
~
Problem3
~
というエラーが出力されました。
メモってなかったので多分になりますが、maatwebsite/excelをインストールする際composer.jsonに記載のframeworkのバージョンだとインストール出来ない的な内容だったかと思います。
なので、maatwebsite/excelをインストールする前に以下のLaravelのアップデートコマンドを実行しました。
php /home/{サーバー契約ユーザー名}/www/{laravel稼働ディレクトリ}/composer.phar update
その後、「maatwebsite/excelインストールコマンドを実行(さくらのレンタルサーバー)」を行うとmaatwebsite/excelがインストールできました。
設定ファイル(/config/app.php)にサービスプロパイダとファサードを登録
/config/app.phpファイルのproviders箇所に以下を記述します。
'providers' => [ ~ Maatwebsite\Excel\ExcelServiceProvider::class, ],
/config/app.phpファイルのaliases箇所に以下を記述します。
'aliases' => [ ~ 'Excel' => Maatwebsite\Excel\Facades\Excel::class, ],
Laravelが稼働しているディレクトリに移動(cd)し、以下のartisanコマンドを実行します。
php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider"
artisanコマンドを実行すると
/config/execl.php
にexecl.phpファイルが生成されます。
エクセル出力を行うusersテーブルを用意
以下のusersテーブルを用意しました。
usersテーブル
名前 | 説明 |
---|---|
id | 主キー |
name | ユーザー名 |
メールアドレス |
usersテーブルの内容を全てveiwに出力するclassを作成
usersテーブルの内容を全てveiw(exports/users.blade.php)に出力する以下のclass(/app/Exports/UsersExport.phpファイル)を作成します。
<?php namespace App\Exports; use Maatwebsite\Excel\Concerns\FromView; use Illuminate\Contracts\View\View; use App\User; class UsersExport implements FromView { public function view(): View { return view('exports.users', [ 'users' => User::all() ]); } } ?>
エクセルファイル出力内容のview(/exports/users.blade.phpファイル)の記述
エクセルファイルに出力する内容のview(/resources/views/exports/users.blade.phpファイル)の記述は以下の通りです。「name」と「email」をエクセルに出力します。
<p>userテーブル</p> <table> <thead> <tr> <th>Name</th> <th>Email</th> </tr> </thead> <tbody> @foreach($users as $user) <tr> <td>{{ $user->name }}</td> <td>{{ $user->email }}</td> </tr> @endforeach </tbody> </table>
エクセルファイル(users.xlsx)を出力するControllerの記述
usersテーブルの内容をエクセルファイル(users.xlsx)に出力するController(/app/Http/Controllers/UsersController.phpファイル)の記述は以下の通りです。
<?php namespace App\Http\Controllers; use App\Exports\UsersExport; use Maatwebsite\Excel\Facades\Excel; class UsersController extends Controller { public function export(){ return Excel::download(new UsersExport, 'users.xlsx'); } } ?>
エクセル出力URL(/routes/web.php)の記述
エクセル(users.xlsx)出力URLを/routes/web.phpに記述します。
<?php Route::get('/usersexport', 'UsersController@export'); ?>
エクセル出力結果
以下のURLを叩くと、エクセルファイル「users.xlsx」がダウンロードされます。
https:// ~ /usersexport
「users.xlsx」出力結果イメージは以下の通りです。
※流用される場合は自己責任でお願いします。