云迈博客

您现在的位置是:首页 > 后端开发 > PHP > 正文

PHP

fastadmin+ phpofficeExcel表格单列多图导入功能

阳帅2022-04-01PHP609
publicfunctionimport(){$file=$this-˃request-˃request('file');if(!$file
 public function import()
    {
        $file = $this->request->request('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();
    }
        $PHPExcel = IOFactory::load($filePath);

        $sheet = $PHPExcel->getSheet(0);
        $highestRow = $sheet->getHighestRow();
        $highestColumn = $sheet->getHighestColumn();

        $tmp = [];
        // 获取一行的数据
        for ($row = 1; $row <= $highestRow; $row++) {
            // Read a row of data into an array
            $rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, NULL, TRUE, TRUE);
            //这里得到的rowData都是一行的数据,得到数据后自行处理,我们这里只打出来看看效果
            // var_dump($rowData);
            // echo "<br>";
            $tmp[] = $rowData[0];
        }
        //打印Excel里面信息的数组
        //循环Excel 内容数据
        $insertarr = [];
        $images = [];
        foreach ($PHPExcel->getSheet(0)->getDrawingCollection() as $k => $drawing) {

            $codata = $drawing->getCoordinates(); //得到单元数据 比如G2单元
            $filename = $drawing->getIndexedFilename();  //文件名
            ob_start();
            call_user_func(
                $drawing->getRenderingFunction(),
                $drawing->getImageResource()
            );
            $imageContents = ob_get_contents();
            $images[] = $codata . '_' . $filename;
            file_put_contents(ROOT_PATH . 'public/uploads/' . $codata . '_' . $filename, $imageContents); //把文件保存到本地
            ob_end_clean();

        }
        $num = 0;
        $imgk = 0;
        foreach ($tmp as $key => $val) {
                #数据库常规数据渲染
            if ($key != 0) {
                $insertarr[$key]['name'] = $tmp[$key][0];
                $insertarr[$key]['mobile'] = $tmp[$key][1];
                $insertarr[$key]['code'] = $tmp[$key][2];
                $insertarr[$key]['goods_name'] = $tmp[$key][4];
                $insertarr[$key]['goods_sku'] = $tmp[$key][5];
                $insertarr[$key]['factory'] = $tmp[$key][6];
                $insertarr[$key]['pihao'] = $tmp[$key][7];
                $insertarr[$key]['amount'] = $tmp[$key][8];
                $insertarr[$key]['unit'] = $tmp[$key][9];
                $insertarr[$key]['wuliutype'] = $tmp[$key][11];
                $insertarr[$key]['deliverytime'] = $tmp[$key][12];
                $insertarr[$key]['site_mobile'] = $tmp[$key][13];
                $insertarr[$key]['site'] = $tmp[$key][14];
                $insertarr[$key]['agent'] = $tmp[$key][15];

                #保存对应列图片地址
                if ($num == 0) {
                    $insertarr[$key]['sales_ticket'] = "/uploads/" . $images[$imgk];
                    $num++;
                    $imgk++;
                }
                if ($num == 1) {
                    $insertarr[$key]['wuliu'] = "/uploads/" . $images[$imgk];
                    $num = 0;
                    $imgk++;
                }
                $insertarr[$key]['createtime'] = time();
                $insertarr[$key]['updatetime'] = time();
            }
        }
        $insertarr = array_values($insertarr);

        Db::startTrans();
        try {
            $relation = [];
            foreach ($insertarr as $key => $value) {
                $data = $this->model->insertGetId($value);
                $agent = explode(':', $value['agent']);

                if (!empty($agent)) {
                    if (is_array($agent)) {
                        foreach ($agent as $k=> $val) {
                            $user = User::get(['mobile' => $val]);
                            if ($user) {
                                $relation[$k]['user_ids'] = $user['id'];
                                $relation[$k]['order_id'] = $data;
                            }
                        }
                    }else{
                        $user = User::get(['mobile' => $agent]);
                        if ($user) {
                            $relation['user_ids'] = $user['id'];
                            $relation['order_id'] = $data;
                        }
                    }

                    if (!empty($relation)) {
                        $SalesRelation = new \app\common\model\SalesRelation();
                        $res = $SalesRelation->saveAll($relation);

                    }

                }


            }
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            exit(json_encode(['code' => 0, 'msg' => $e->getMessage()]));
        }
        $this->success();
    }

发表评论

评论列表

  • 这篇文章还没有收到评论,赶紧来抢沙发吧~