4
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

laravel5.8でExcelお手軽ダウンロード

Last updated at Posted at 2019-05-25

バージョン

  • laravel5.8
  • maatwebsite/excel3.1

今回は練習例題として、日数をExcelでダウンロードさせたいと思います。
こちらの記事を参考にさせていただきます。

準備

「Laravel Excel」パッケージをインストールします
PhpSpreadsheetを元に作成されたLaravelでExcelを扱うときの便利ライブラリ

コマンド
composer require maatwebsite/excel

docker環境でエラーが出る場合

こんな感じのエラー
- phpoffice/phpspreadsheet 1.6.0 requires ext-gd * -> the requested PHP extension gd is missing from your system.
    - phpoffice/phpspreadsheet 1.5.2 requires ext-gd * -> the requested PHP extension gd is missing from your system.
    - phpoffice/phpspreadsheet 1.5.1 requires ext-gd * -> the requested PHP extension gd is missing from your system.
    - phpoffice/phpspreadsheet 1.5.0 requires ext-gd * -> the requested PHP extension gd is missing from your system.
    - phpoffice/phpspreadsheet 1.4.1 requires ext-gd * -> the requested PHP extension gd is missing from your system.
    - phpoffice/phpspreadsheet 1.4.0 requires ext-gd * -> the requested PHP extension gd is missing from your system.
    - Installation request for maatwebsite/excel ^3.1 -> satisfiable by maatwebsite/excel[3.1.0, 3.1.1, 3.1.10, 3.1.11, 3.1.12, 3.1.13, 3.1.2, 3.1.3, 3.1.4, 3.1.5, 3.1.6, 3.1.7, 3.1.8, 3.1.9, 3.1.x-dev, 3.2.x-dev].

  To enable extensions, verify that they are enabled in your .ini files:
    - /usr/local/etc/php/php.ini
    - /usr/local/etc/php/conf.d/docker-php-ext-mysqli.ini
    - /usr/local/etc/php/conf.d/docker-php-ext-pdo_mysql.ini
    - /usr/local/etc/php/conf.d/docker-php-ext-sodium.ini
    - /usr/local/etc/php/conf.d/docker-php-ext-zip.ini
  You can also run `php --ini` inside terminal to see which files are used by PHP in CLI mode.

Installation failed, reverting ./composer.json to its original content.

依存関係エラーらしいので[https://translate.google.com/translate?hl=ja&sl=en&u=https://github.com/nanoninja/docker-nginx-php-mysql/issues/28&prev=search]

コマンド
composer require maatwebsite/excel --ignore-platform-reqs

これで、インストール系の準備は整いました。

##Facadeを利用しない

日数をexportするためのファイルを作成します。

コマンド
php artisan make:export DateExport

Exports/DateExport.phpが作成されたと思います。

DateExport.php
<?php

namespace App\Exports;

use Maatwebsite\Excel\Concerns\FromCollection;

class DateExport implements FromCollection
{
    public function collection()
    {
        
    }
}

FromCollectionはcollectionメソッドの中に、Collectionのデータをいれてそのままダウンロードできます。(例:Model::all()など)
今回は、1~31を記述します。注意点としては、Modelの取得データをそのまま返したりできるため、collectionメソッドには、多次元で記述する必要があります。(FromArrayを使った場合も)

-- あるModelクラスの取得データ例 --
Screenshot_1.png

日付1から31まで記述して出してみます。

DateExport.php
<?php

namespace App\Exports;

use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromCollection;

class DateExport implements FromCollection
{
    use Exportable;

    public function collection()
    {
        return collect(
            [
                0 => [
                    range(1, 31)
                ]
            ]
        );
    }
}

ポイントとしては、use Exportableを使うと、Excelファサードを用意しないでも、Excelファイルをダウンロードさせることができます。
range関数で1~31までの配列を用意しています。
あとは、ルートを用意するだけですね。

web.php
Route::get('export', 'SampleController@export');
SampleController.php
<?php

namespace App\Http\Controllers;

use App\Exports\DateExport;

class SampleController extends Controller
{
    public function export(){
        return (new DateExport())->download('date.xlsx' ) ;
    }
}

DateExportクラスをインスタンス化して、downloadメソッドを呼んでいます。use Exportableを記述しているおかげで、downloadメソッドを使用できます。
また、csvやほかの形でダウンロードしたい場合も、ファイル名を変えれば可能です。pdfは別パッケージをすれば、ダウンロードできます

早速アクセスしてみます。

Screenshot_2.png

こんな感じになります。1 => [range(1, 31)]を記述すれば、2行になります(0=>の中にrange(1,31)を入れても2行にできる)

##Facadeを利用する

Facadeを利用するために、ProviderとExcelクラスの登録を行います。

config/app.php
'providers' => [

    Maatwebsite\Excel\ExcelServiceProvider::class,

],
'aliases' => [

    'Excel' => Maatwebsite\Excel\Facades\Excel::class,

],

設定ファイル(excel.php)を作成し、キャッシュをクリアしときます。

コマンド
php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider"
php artisan config:cache

excel.phpの説明

Facadeを利用しないで、作成したDateExportをそのまま利用して、SampleControllerだけ変更します。

SampleController
<?php

namespace App\Http\Controllers;

use App\Exports\DateExport;
use Maatwebsite\Excel\Facades\Excel;

class SampleController extends Controller
{
    public function export(){
        return Excel::download(new DateExport(), 'date.xlsx');
    }
}

Excelファサードを利用するようにしましたので、DateExportのuse Exportable;の記述を消してもダウンロードできます。
あとは、アクセスすればダウンロードできます。

ほかにも、viewからダウンロードする方法なんかもあるらしいです。

##まとめ
すごく簡単にできた。先人の人たちありがとうございます。
この後は、これを生かして、Sheetを複数にしたり、Excelファイルのセルの背景色をいじったりして、もっとデータを見やすく、自動で出せるものを作成していきたいと思います。

4
6
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
4
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?