tp5 使用phpexcel將excel表格的導入數據庫

參考地址:https://blog.csdn.net/qq_37138818/article/details/81093302php

1--使用composer安裝phpexcel包thinkphp

composer require phpoffice/phpexcel -vvv數組

2-控制器composer

 //導入數據
    public function insertExcel(){
        if(request() -> isPost())
        {
            vendor("PHPExcel.PHPExcel"); //方法一
            $objPHPExcel =new \PHPExcel();
            //獲取表單上傳文件
            $file = request()->file('excel');
            $info = $file->validate(['ext' => 'xlsx'])->move(ROOT_PATH . 'public');  //上傳驗證後綴名,以及上傳以後移動的地址  E:\wamp\www\bick\public
            if($info)
            {
//              echo $info->getFilename();
                $exclePath = $info->getSaveName();  //獲取文件名
                $file_name = ROOT_PATH . 'public' . DS . $exclePath;//上傳文件的地址
                $objReader =\PHPExcel_IOFactory::createReader("Excel2007");
                $obj_PHPExcel =$objReader->load($file_name, $encode = 'utf-8');  //加載文件內容,編碼utf-8
                $excel_array=$obj_PHPExcel->getSheet(0)->toArray();   //轉換爲數組格式
                array_shift($excel_array);  //刪除第一個數組(標題);
                $city = [];
                $i=0;
                foreach($excel_array as $k=>$v) {
                    $city[$k]['id'] = $v[0];
                    $city[$k]['phone'] = $v[1];
                    $city[$k]['username'] = $v[2];
                    $city[$k]['nickname'] = $v[3];
                    $city[$k]['end_time'] = $v[4];
                    $city[$k]['level'] = $v[5];
                    $i++;
                }
                Db::name("users")->insertAll($city);
            }else
            {
                echo $file->getError();
            }
        }
        return $this->fetch("user-excel");
    }

 

參考地址:https://www.kancloud.cn/he_he/thinkphp5

thinkphp5

相關文章
相關標籤/搜索