(1)直接到项目根目录composer安装maatwebsite/excel包
composer require maatwebsite/excel
(2)创建导入类
php artisan make:import UsersImport --model=User
找到生成的文件
app/Imports/UsersImport.php
<?php
namespace App\Imports;
use App\Models\User;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
class UsersImport implements ToModel, WithHeadingRow
{
/**
* @param array $row
*
* @return \Illuminate\Database\Eloquent\Model|null
*/
public function model(array $row)
{
//导入的数据
return new User([
'name' => $row['name'],
'email' => $row['email'],
'password' => \Hash::make($row['password']),
]);
}
}
(3)创建导出类
php artisan make:export UsersExport --model=User
找到生成的文件
app/Exports/UsersExport.php
<?php
namespace App\Exports;
use App\Models\User;
use Maatwebsite\Excel\Concerns\FromCollection;
class UsersExport implements FromCollection
{
/**
* @return \Illuminate\Support\Collection
*/
public function collection()
{
//导出的模型数据
return User::all();
}
}
(4)控制器方法
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Exports\UsersExport;
use App\Imports\UsersImport;
use Maatwebsite\Excel\Facades\Excel;
class MyController extends Controller
{
/**
* @return \Illuminate\Support\Collection
*/
public function export()
{
//导出方法
return Excel::download(new UsersExport, 'users.xlsx');
}
/**
* @return \Illuminate\Support\Collection
*/
public function import()
{
//导入方法
Excel::import(new UsersImport,request()->file('file'));
return back();
}
}