fastadmin导入excel

在对应控制层加上2个方法import跟readFile,注意需要把对应的方法引入一下

/**
     * 重写import方法
     */
    public function import()
    {
        $file = $this->request->request('file'); //'file'为文件字段名
        $data = $this->readFile($file);
        if (count($data) <= 0) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        /*处理data数据*/
        $nfc_num = 0;//需要投送的NFC数量(总数)
        foreach ($data as $k=>$v){
            $data[$k]['createtime'] = time();
            $data[$k]['admin_id'] = $this->auth->getUserInfo()['id'];
            $data[$k]['type'] = 2;
            $nfc_num += $v['nfc_num'];
        }
        if ($nfc_num <= 0){
            $this->error('NFC数量不能小于0');
        }
        $nfc_total = $this->configModel::getConfigField('nfc_total');//NFC总量
        if ($nfc_total <= 0){
            $this->error('NFC总量余量不足');
        }
        if ($nfc_total < $nfc_num){
            $this->error('NFC总量不足投送');
        }

        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
//            dump($data);exit();
            $result = $this->model->allowField(true)->saveAll($data);
            $this->configModel = new Config();
            $this->configModel::upDateConfigField('nfc_total',-$nfc_num);
            foreach ($data as $param) {
                change_user_nft_token($param['user_id'],$param['nfc_num'],'管理员投送');
            }
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }
/**
     * 读取文件数据并返回
     * @return array
     */
    protected function readFile($file){
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, "w");
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding != 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }

        //加载文件
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);

            //读取第一行字段名
            $fields = [];
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $fields[] = $val;
                }
            }

            //读取行数据
            $row = [];
            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $values[] = is_null($val) ? '' : $val;
                }

                $row[] = array_combine($fields, $values);
            }
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }

        if (!$row) {
            $this->error(__('No rows were updated'));
        }
        return $row;
    }

在模板文件index中添加按钮

{:build_toolbar('import')}

在对应的js文件中添加好请求路径

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值