laravel版本 6.2 不能再指定 maatwebsite/excel 2版本的,而版本3的excel基本方法已经重写了,使用方法也与2.x,大不一样!
目录
1.环境要求:
-
PHP:
^7.0 -
Laravel:
^5.5
2.安装
composer require maatwebsite/excel
不需要在config/app.php中加载配置
3.Excel实现导入
新建导入文件,导入导出业务代码尽量不要和原来业务耦合。我们拿 feedback 模块举例
php artisan make:import FeedbackImport --model=Feedback

会在 app 目录下创建 Exports 目录
app
├── Imports
│ ├── FeedbackImport.php
FeedbackImport 代码内容
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Concerns\ToCollection;
class FeedbackImport implements ToCollection
{
public function collection(Collection $collection)
{
foreach($collection as $item) {
$this->createData($item);
}
}
/**
* 数据业务处理
* @param $rows
*/
public function createData($rows)
{
$insert = [
'uid' => $rows[0],
'phone' => $rows[1],
'tel' => $rows[2],
'content' => $rows[3],
'addtime' => time(),
];
DB::table('feedback')->insert($insert);
}
}
excel 文件内容

导入成功,数据表如下:

4.Excel获取数据,自己实现导入
新建导入文件,导入导出业务代码尽量不要和原来业务耦合。我们拿 feedback 模块举例
php artisan make:import FeedbackImport --model=Feedback
使用标题3创建的FeedbackImport文件亦可。
FeedbackImport 文件代码如下:
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\ToCollection;
class FeedbackImport implements ToCollection
{
// 增加trait调用
use Importable;
业务控制器
use App\Imports\FeedbackImport;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;
class FeedbackController extends AdminBaseController
{
public function importV2()
{
// 项目中的文件路径
$file = './uploads/product_import/20210324/20210324115657897071.xls';
// 读取文件中的内容 转化为数组
$data = (new FeedbackImport())->toArray($file);
if(!empty($data)) {
$arr = $data[0];
foreach($arr as $rows) {
$insert = [
'uid' => $rows[0],
'phone' => $rows[1],
'tel' => $rows[2],
'content' => $rows[3],
'addtime' => time(),
];
DB::table('feedback')->insert($insert);
}
}
}
}
导入成功,数据表如下:

暂时到这里,基本能实现大部分的功能了!
本文介绍了在 Laravel 6.2 环境下,如何升级并使用 Maatwebsite/Excel 的3.0版本进行数据导入。相比于2.x版本,3.0版本的API有所改变,需要使用`Importable` trait。通过创建导入类,实现了从Excel文件中读取数据并插入到数据库的操作。同时,提供了数据导入的示例代码和实际效果展示。
888

被折叠的 条评论
为什么被折叠?



