๋ฐ์ํ
์ค์น
์์ ํจํค์ง ์ค์น
composer require maatwebsite/excel
config/app.php ํ์ผ ์์
'providers' => [
/*
* Package Service Providers...
*/
Maatwebsite\Excel\ExcelServiceProvider::class,
],
'aliases' => [
'Excel' => Maatwebsite\Excel\Facades\Excel::class,
]
venter publich ๋ช ๋ น์ด ์คํ
php artisan vendor:publish
> ์คํํ Provider: Maatwebsite\Excel\ExcelServiceProvider ์ ๋ฒํธ ์ ๋ ฅํ๊ณ ์ํฐ
์ฝ์ ํ ์์ ํ์ผ
ํ ์ด๋ธ
DB์ ๋ฐ๋ก importํ๊ธฐ
conrtoller, model, import ์์ฑ
php artisan make:controller TestController
php artisan make:model TestTable
php artisan make:import TestImport --model=TestTable
Controllers/TestController
<?php
namespace App\Http\Controllers;
use App\Imports\TestImport;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
class TestController extends Controller
{
public function testImport()
{
Excel::import(new TestImport, 'test.xlsx');
return '์ฑ๊ณต';
}
}
Models/TestTable
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class TestTable extends Model
{
use HasFactory;
protected $table = "Test_table";
public $timestamps = false; //created_at, updated_at ์ปฌ๋ผ ์ฌ์ฉ ์ํจ
protected $fillable = [
'name',
'nickname',
'phone',
'address',
];
}
Imports/TestImport
<?php
namespace App\Imports;
use App\Models\TestTable;
use Maatwebsite\Excel\Concerns\ToModel;
class TestImport implements ToModel
{
/**
* @param array $row
*
* @return \Illuminate\Database\Eloquent\Model|null
*/
public function model(array $row)
{
return new TestTable([
'name' => $row[0],
'nickname' => $row[1],
'phone' => $row[2],
'address' => $row[3],
]);
}
}
routes/api
Route::get('/test', [TestController::class, 'testImport']);
์คํ
๋ฐฐ์ด๋ก ์ถ๋ ฅํ๊ธฐ
controller, import ์์ฑ
php artisan make:controller TestController
php artisan make:import TestArrayImport
Controllers/TestController
<?php
namespace App\Http\Controllers;
use App\Imports\TestArrayImport;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
class TestController extends Controller
{
public function testArray()
{
$array = Excel::toArray(new TestArrayImport, 'test.xlsx');
return $array;
}
}
Imports/TestArrayImport
<?php
namespace App\Imports;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
class TestArrayImport implements ToCollection
{
/**
* @param Collection $collection
*/
public function collection(Collection $collection)
{
//
}
}
route/api
Route::get('/test-array', [TestController::class, 'testArray']);
์คํ
๋ฐ์ํ
'๐Framework > ๐ต Laravel' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Laravel] ๋ผ๋ผ๋ฒจ์ swagger ์ ์ฉํ๊ธฐ (0) | 2023.04.21 |
---|---|
[Laravel] Serialization of 'Illuminate\\Http\\UploadedFile' is not allowed ์๋ฌ (0) | 2023.03.08 |
[Laravel] Maximum execution time of 60 seconds exceeded ์๋ฌ (0) | 2022.05.24 |
[Laravel] layout (0) | 2021.11.17 |
[Laravel] routes (0) | 2021.11.17 |