开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 19 天,点击查看活动详情
Excel导入和导出都是很常见的场景,之前用过phpexcel,总感觉太过繁琐,印象中phpexcel也很久没更新,看到 Laravel 项目中有小伙伴使用Maatwebsite\Excel,便尝试使用一下。
现将使用步骤记录如下:(Laravel6.x版本)
安装
composer require maatwebsite/excel
导入
生成导入类
php artisan make:import AdminsImport --model=Admin
此命令会app 下面生成或对应的文件,如果没有 Imports 文件夹,也会一起生成。
完善业务逻辑
<?php
namespace App\Imports;
use App\Models\Admin;
use function EasyWeChat\Kernel\Support\str_random;
use Maatwebsite\Excel\Concerns\ToModel;
class AdminsImport implements ToModel
{
/**
* @param array $row
*
* @return \Illuminate\Database\Eloquent\Model|null
*/
public function model(array $row)
{
//过滤表头和空行,我这边表头的第一个单元格是id,具体自行调整
if (empty($row[0]) || $row[0] == 'id') {
return null;
}
return new Admin([
'username' => $row[2],
'password' => bcrypt($row[3]),
'api_token' => str_random(60),
]);
}
}
逻辑比较鸡蛋,就是过滤表头,然后处理激烈数据。
导入任务
我们在 Command 新建 ImportAdmin,代码如下:
<?php
namespace App\Console\Commands;
use App\Imports\AdminsImport;
use Illuminate\Console\Command;
use Maatwebsite\Excel\Facades\Excel;
class ImportAdmin extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'importAdmin';
/**
* The console command description.
*
* @var string
*/
protected $description = '导入admin';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
Excel::import(new AdminsImport(), storage_path('files/export.xlsx'));
$this->info($this->description.'完成');
}
}
其他逻辑
如果你的业务必不仅仅是写入数据,有一些涉及具体业务的操作,那么你可以这样操作。
<?php
namespace App\Imports;
use App\Models\Admin;
use function EasyWeChat\Kernel\Support\str_random;
use Maatwebsite\Excel\Concerns\ToCollection;
use Illuminate\Support\Collection;
class AdminsImport implements ToCollection
{
public function collection(Collection $rows)
{
//如果需要去除表头
unset($rows[0]);
//$rows 是数组格式
return $this->createData($rows);
}
public function createData($rows)
{
$success = 0;
foreach ($rows as $row) {
$row[0] = (int) $row[0];
if (empty($row[0])) {
continue;
}
(new Admin())->create(
[
'username' => $row[2],
'name' => $row[2],
'password' => bcrypt($row[3]),
'api_token' => str_random(60),
]
);
// 其他业务代码
$success++;
}
return $success.'-'.count($rows);
}
}
可以在其他业务代码部分补充你的逻辑代码。
执行
php artisan importAdmin
这样一个完整的导入任务就完成了。总的来说,使用起来还是简单明了的。
more
具体导入实现可以搜索Maatwebsite\Excel\Excel查看,里面还有导出、以队列方式导入等,支持的格式也是多种多样,具体代码可自行查看,功能还是很强大的,足够应付日常需求了。
参考: