1
4

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.

Laravel6+Laravel-Excel3.1でアップロードしたExcelファイルを解析して内容をDB登録する場合

Posted at

あまりExcelファイルからのデータをDB取込する場合の情報がなかったので執筆

準備

依存対応

Laravelが動いてる環境でLaravel-Excelをインストールする際php-gdがないというエラーが出る場合がある為ない場合予めインストールしておく

# yum install --enablerepo=remi-php73 php-gd

※php7.3を使用している場合

ComposerでのLaravel-Excelのインストール

$ composer require maatwebsite/excel

ファサードを登録

config/app.php
    'providers' => [
+        Maatwebsite\Excel\ExcelServiceProvider::class,
    ],
    'aliases' => [
+        'Excel' => Maatwebsite\Excel\Facades\Excel::class,
    ],

設定ファイルの生成

php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider"

実行プログラム

※アップロードフォームおよびルーティングは省略

インポートクラスの作成

Excel内のデータを配列に変換する場合のインポートクラス

php artisan make:import DirectImport
<?php
namespace App\Imports;
use Maatwebsite\Excel\Concerns\ToModel;
use Excel;
class DirectImport implements ToModel
{
    public function model(array $row)
    {
        return $row;
    }
}

コントローラーでの処理

app/Http/Controllers/XxxxxController
<?php
namespace App\Http\Controllers;
use App\Imports\DirectImport;
use Excel;
use Illuminate\Http\Request;
class XxxxxController extends Controller
{
    public function import(Request $request)
    {
        $file = $request->file('file');
        $book = Excel::toArray(new DirectImport(), $file->getPathname(),null,\Maatwebsite\Excel\Excel::XLSX);
        $sheet = $book[0];
        // $sheet[0][0] → A1セルなど必要な値を取り出してDBへ書き込む処理を行う
        //
        // …
        //
        return $request->all();
    }
}
1
4
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
1
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?