• Laravel :如何将Excel文件导入数据库


    一、前提

    想要将excel内容入库,laravel有扩展可以使用,常用的扩展是maatwebsite/excel,安装步骤参考上一篇:laravel中安装Maatwebsite/excel扩展

    二、使用

    2.1、新建一个导入文件

    php artisan make:import 文件名称 --model=Model地址
    

    在这里插入图片描述

    然后在里边编写你的导入逻辑

    <?php
    
    namespace App\Imports;
    
    use App\Exceptions\ApiException;
    use Illuminate\Support\Facades\DB;
    use Maatwebsite\Excel\Concerns\ToArray;
    use Maatwebsite\Excel\Concerns\WithChunkReading;
    use Maatwebsite\Excel\Concerns\WithHeadingRow;
    
    class QuesExport implements ToArray, WithChunkReading, WithHeadingRow
    {
    
        public function array(array $rows)
        {
            $data = [];
            $now = date('Y-m-d H:i:s');
            foreach ($rows as $row) {
    
                $data[] = [
                    'id' => $row['id'],
                    'number' => 0,
                    'parent_id' => 0,
                    'type' => 1,
                    'question' => $row['ques'],
                    'standard_answer' => $row['answer'],
                    'ai_ques_id' => $row['aiid'],
                    'created_at' => $now
                ];
            }
    
            if (!$data) {
                throw new ApiException('没有要导入的数据');
                return false;
            };
    
            //全部导入
            DB::select('TRUNCATE table questions_copy1');
    
            DB::table('questions_copy1')->insert($data);
    
            return true;
        }
    
        public function chunkSize(): int
        {
            return 500;
        }
    
        public function headingRow(): int
        {
            return 1;
        }
    
        /**
         * @param Failure[] $failures
         */
        public function onFailure(Failure ...$failures)
        {
            // Handle the failures how you'd like.
            throw new ApiException('fhwaeurewsdf');
        }
    }
    
    

    2.2、新建一个控制器和方法,调用导入文件

        /**
         * 导入excel,入库
         *
         * */
        public function uploadQues(Request $request){
            $file = $request->file('file');
    
            // 保存上传文件
            $path = public_path('uploads/admin/ques');
            $this->mkdirs($path); // 已存在的路径不会再创建
            $fileName = date('YmdHis') . '_' . uniqid() . '_' . '.' . strtolower($file->getClientOriginalExtension());
            $file->move($path, $fileName);
    
            // 读取文件并入库
            Excel::import(new QuesExport(), $path . '/' . $fileName);
    
            // 删除上传文件
            unlink($path . '/' . $fileName);
    
            return response()->json([
                'status'=>1,
                'msg'=>'',
            ]);
        }
    

    2.3、 新建一个页面,支持文件上传

    我这里简单写了个页面,如下:

    <!DOCTYPE html>
    <html >
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
    
        <title>Laravel</title>
        <script  src="/js/jquery-3.3.1.min.js?v=2021123999" type="text/javascript" charset="utf-8"></script>
    
        <meta name="csrf-token" content="{{ csrf_token() }}">
    </head>
    <body>
    <div class="flex-center position-ref full-height">
        <div class="upload_box">
            <input type="file" name="file" accept="file" id="auth-upload"  onchange="uploadFile();"/>
            <div class="reload_file flex-v flex-vc flex-hc">
                <i class="icon icon_add"></i>
                <p>文件</p>
            </div>
        </div>
    </div>
    
    <script>
    
        function uploadFile(){
            file = $("#auth-upload")[0].files[0];
    
            // alert(file);
            // alert(file.name);
            // return;
            file_name = file.name;
            ext = file_name.slice(file_name.lastIndexOf(".")+1).toLowerCase();
            imgMaxSize = 1024*1024*10;
            if (ext != 'xlsx' ) {swal('文件格式不正确');return ;}
            // if (file.size > imgMaxSize) {swal('文件大小超过10M'); return ;}
    
            formData = new FormData();
            // 自定义formData中的内容
            formData.append('file', file);
            formData.append('_token', '{{csrf_token()}}');
    
            $.ajax({
                type: 'POST',
                url: "/upload",
                data: formData,
                cache: false,
                processData: false,
                contentType: false,
                dataType:'json',
                success: function (data) {
                    if (data.status){
                      alert('成功');
                    }else{
                        alert('失败');
    
                    }
                }
            });
        }
    
    
    
    </script>
    </body>
    </html>
    
    
    
  • 相关阅读:
    C++11 - 7 - 线程库
    Docker基础
    shell脚本—— case语句+函数
    SpringBoot如何动态更新yml文件?
    【大模型AIGC系列课程 3-8】AI 代理的应用
    Kafka的 ISR 概念和作用
    UniApp 中的路由魔法:玩转页面导航与跳转
    【RabbitMQ】——主题模式(Topics)
    window的addEventListener和removeEventListener方法的使用踩雷
    WebSocket
  • 原文地址:https://blog.csdn.net/snow_love_xia/article/details/140373305