Laravel-Excel 是一個在Laravel 內處理Excel的套件。使用方法挺容易的,官網教學也清楚,這邊簡單介紹一下匯入功能。

Github
https://github.com/Maatwebsite/Laravel-Excel

Install

composer require maatwebsite/excel

在 config/app.php內加入 ServiceProvider

Maatwebsite\Excel\ExcelServiceProvider::class,

也可以加入aliases內使用 facade 功能。

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

加入excel.php設定

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

新增 Import Class

php artisan make:import ContactsImport --model=Contact

修改匯入順序

<?php

namespace App\Imports;

use App\Contact;
use Illuminate\Support\Facades\Hash;
use Maatwebsite\Excel\Concerns\ToModel;

class ContactsImport implements ToModel
{
    /**
     * @param array $row
     *
     * @return Contact|null
     */
    public function model(array $row)
    {
        return new Contact([
           //於此處填寫匯入順序如下
           'name'   => $row[0],
           'phone'  => $row[1], 
           'email'  => $row[2]
        ]);
    }
}

建立控制器

php artisan make:controller ContactController

處理EXCEL資料匯入

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Imports\ContactsImport;
use App\Exports\ContactsExport;
use Maatwebsite\Excel\Facades\Excel;
use Log;

class ContactController extends Controller
{
    public function index(){
        return view('ImportExport.import');
    }
    public function import(Request $request) 
    {
        try{
            if ($request->hasFile('myfile')){
                $file = $request->file('myfile');
                if ($request->file('myfile')->isValid())
                {
                    Excel::import(new ContactsImport, $file);
                    return redirect()->back()->with('success', 'All data successfully imported!');
                }
            }
        }catch(\Exception $ex){
            Log::info($ex);
        }
    }
    
    public function export() 
    {
        return Excel::download(new ContactsExport, 'contacts.xlsx');
    }
}

View 建立

<form method="POST" action="{{ route('import')}}" enctype="multipart/form-data">
@csrf
<label for="myfile">Select a file:</label>
<input type="file" id="myfile" name="myfile" accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel">
<input type="submit">
</form>

 

參考出處:
1、 https://laravelarticle.com/laravel-excel-import-export
2、 https://dustinhsiao21.com/2018/03/15/use-maatwebsite-laravel-excel-import/

創作者介紹
創作者 Kuma 熊本部 的頭像
KumaChen

Kuma 熊本部

KumaChen 發表在 痞客邦 留言(1) 人氣( 784 )