/**
     * 文件转arr
     * $fieldArr=["名称1"=>name1,"名称2"=>name2]
     * $extend 合并的扩展数据数值如 $extend["time"]=time()
     * @return void
     * @throws PDOException
     * @throws BindParamException
     */
    protected function filetoarr($file,$fieldArr,$extend)
    {
       // $file = $this->request->request('file');
        if (!$file) {
            $this->error("导入的文件不能为空");
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('导入的文件不能为空!'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('不支持的格式,请上传xls或xlsx'));
        }
        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();
        }
        //加载文件
        $insert = [];
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('加载错误'));
            }
            $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[] = isset($fieldConvert[$val]) ? $fieldConvert[$val] : $val;  //转换说明文字为字段名称
                }
            }

            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 = [];
                $temp = array_combine($fields, $values);

                foreach ($temp as $k => $v) {
                    if (isset($fieldArr[$k]) && $k !== '') {
                        $row[$fieldArr[$k]] = $v;  //替换表格字段头未数据库字段头,并赋值数据
                    }
                }
                if ($row) {
                    $insert[] = array_merge($row, $extend); //合并扩展数据
                }

            }
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
        if (!$insert) {
            $this->error(__('未成功导入数据'));
        }
        return $insert;
       
    }

快捷键:daoruxls

源:

sublime_text格式

<snippet>
    <content><![CDATA[
/**
     * 文件转arr
     * \$fieldArr=["名称1"=>name1,"名称2"=>name2]
     * \$extend 合并的扩展数据数值如 \$extend["time"]=time()
     * @return void
     * @throws PDOException
     * @throws BindParamException
     */
    protected function filetoarr(\$file,\$fieldArr,\$extend)
    {
       // \$file = \$this->request->request('file');
        if (!\$file) {
            \$this->error("导入的文件不能为空");
        }
        \$filePath = ROOT_PATH . DS . 'public' . DS . \$file;
        if (!is_file(\$filePath)) {
            \$this->error(__('导入的文件不能为空!'));
        }
        //实例化reader
        \$ext = pathinfo(\$filePath, PATHINFO_EXTENSION);
        if (!in_array(\$ext, ['csv', 'xls', 'xlsx'])) {
            \$this->error(__('不支持的格式,请上传xls或xlsx'));
        }
        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();
        }
        //加载文件
        \$insert = [];
        try {
            if (!\$PHPExcel = \$reader->load(\$filePath)) {
                \$this->error(__('加载错误'));
            }
            \$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[] = isset(\$fieldConvert[\$val]) ? \$fieldConvert[\$val] : \$val;  //转换说明文字为字段名称
                }
            }

            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 = [];
                \$temp = array_combine(\$fields, \$values);

                foreach (\$temp as \$k => \$v) {
                    if (isset(\$fieldArr[\$k]) && \$k !== '') {
                        \$row[\$fieldArr[\$k]] = \$v;  //替换表格字段头未数据库字段头,并赋值数据
                    }
                }
                if (\$row) {
                    \$insert[] = array_merge(\$row, \$extend); //合并扩展数据
                }

            }
        } catch (Exception \$exception) {
            \$this->error(\$exception->getMessage());
        }
        if (!\$insert) {
            \$this->error(__('未成功导入数据'));
        }
        return \$insert;
       
    }
]]></content>
   <tabTrigger>daoruxls(fastadmin导入xls文件数据导入)</tabTrigger>
   <scope></scope>
</snippet>
点赞(0)

评论列表 共有 0 条评论

暂无评论
立即
投稿
发表
评论
返回
顶部