当前位置 博文首页 > json_li的博客:Laravel Excel 3.1 导入

    json_li的博客:Laravel Excel 3.1 导入

    作者:[db:作者] 时间:2021-08-25 15:49

    laravel版本 6.2 不能再指定 maatwebsite/excel 2版本的,而版本3的excel基本方法已经重写了,使用方法也与2.x,大不一样!

    目录

    1.环境要求:

    2.安装

    3.Excel实现导入

    4.Excel获取数据,自己实现导入


    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);
                }
            }
        }
    }

    导入成功,数据表如下:

    暂时到这里,基本能实现大部分的功能了!

    借鉴文章:https://learnku.com/articles/32400

    cs
    下一篇:没有了