php Excel 导入


php Excel 导入

    public function storeSql()
    {
        $file = input('file.excel');
        $path = ROOT_PATH . 'public' . DS . 'uploads';
        if ($file) {
            $info = $file->move($path);
            if ($info) {
                $this->dataStore($info->getPathname());
            } else {
                $this->error($file->getError());

            }
        }

    }

    //数据导入
    public function dataStore($filePath)
    {
        import('phpoffice.phpexcel.Classes.PHPExcel');
        import('phpoffice.phpexcel.Classes.IOFactory');
        import('phpoffice.phpexcel.Classes.Reader.Excel2007');
        $PHPExcel = new \PHPExcel();
        $PHPReader = new \PHPExcel_Reader_Excel2007();
        if (!$PHPReader->canRead($filePath)) {
            $PHPReader = new \PHPExcel_Reader_Excel5();
            if (!$PHPReader->canRead($filePath)) {
                $this->error('上传失败!');
            }
        }
        //读取Excel文件
        $PHPExcel = $PHPReader->load($filePath);
        //读取excel文件中的第一个工作表
        $sheet = $PHPExcel->getSheet(0);
        //取得最大的列号
        $allColumn = $sheet->getHighestColumn();
        //取得最大的行号
        $allRow = $sheet->getHighestRow();
        $user = new UserOff;
        $phones = $user->where('merchant_id', $this->userID)->column('phone');
        $all = [];
        //从第二行开始插入,第一行是列名
        for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
            $data['phone'] = $PHPExcel->getActiveSheet()->getCell("A" . $currentRow)->getValue();
            $data['point'] = $PHPExcel->getActiveSheet()->getCell("B" . $currentRow)->getValue();
            $data['growth'] = $PHPExcel->getActiveSheet()->getCell("C" . $currentRow)->getValue();
            $data['card_num'] = $PHPExcel->getActiveSheet()->getCell("D" . $currentRow)->getValue();
            $data['user_name'] = $PHPExcel->getActiveSheet()->getCell("E" . $currentRow)->getValue();
            $data['merchant_id'] = $this->userID;
            $data['add_time'] = time();
            $data['phone_no'] = $data['phone'] . $this->userID . "AcDE"; //编号
            empty($data['card_num']) && $data['card_num'] = 0;
            empty($data['user_name']) && $data['user_name'] = "";
            empty($data['phone']) && $data['user_name'] = "";
            empty($data['point']) && $data['point'] = 0;
            empty($data['growth']) && $data['growth'] = 0;
            array_push($all,$data);
        }
        $allData =$this->diffArr($all,$phones);

        $update = $user->saveAll($allData['allDataUp'], true);
        //$update = true;
        $insert = $user->saveAll($allData['allDataIn'], false);
        if ($update || $insert) {
            $this->success('数据导入成功!', url('dump/index'));
        } else {
            $this->error('数据导入失败!');
        }
    }

猜你喜欢

转载自blog.csdn.net/w1366352655/article/details/85562853