tp5使用PHPExcel实现excel表格数据导入数据库

一. 前端实现(layui)

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>upload模块快速使用</title>
    <link rel="stylesheet" href="https://www.layuicdn.com/layui/css/layui.css" media="all">
</head>
<body>
    <button type="button" class="layui-btn" id="test1">
        <i class="layui-icon">&#xe67c;</i>上传文件
    </button>

    <script src="https://www.layuicdn.com/layui/layui.js"></script>
    <script>
        layui.use('upload', function(){
            var upload = layui.upload;

            //执行实例
            var uploadInst = upload.render({
                elem: '#test1' //绑定元素
                ,url: '/index.php/admin/excel/excelFileInputDemo' //上传接口
                ,accept: 'file'
                ,done: function(res){
                    //上传完毕回调
                }
                ,error: function(){
                    //请求异常回调
                }
            });
        });
    </script>
    </body>
    </html>

二. 后端实现(tp5 + PHPExcel)

  1. 从提交的缓存文件中获取数据并格式化数据
 /*
     * excel表数据导入
     * */
    public function excelFileInput(){
        $file = $_FILES['file']; //获取上传文件
        $extension = strtolower(pathinfo($file['name'],PATHINFO_EXTENSION));  //pathinfo()函数以数组的形式返回文件路径的信息
        if($extension == "xlsx"){
            //2007(相当于是打开接收的这个excel)
            $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
        }else{
            //2003(相当于是打开接收的这个excel)
            exit(json_encode(['status'=>0, 'msg'=>'不是期望的文件']));
        }
        $objContent = $objReader -> load($file['tmp_name']); //加载缓存文件
        $sheetContent = $objContent -> getSheet(0)  //获取活动的表格
                                    -> toArray();   //  转换成数组
//        dump($sheetContent);

        //提取表名
        $name = explode('.',pathinfo($file['name'],PATHINFO_BASENAME));
        $name_table= $extension = strtolower($name[0]);

        //提取表字段,一维数组
        $field_table = $sheetContent[2]; //2表示excel表格第3行

        //提取数组,二维数组
        $data_table = [];
        for($i=3, $n=count($sheetContent);$i<$n;$i++){
            $tableDataItem = [];
            foreach ($field_table as $key=>$value){
                $tableDataItem[$value] = $sheetContent[$i][$key];
            }
            array_push($data_table, $tableDataItem);
        }
        $this->inputDb( $name_table, $field_table, $data_table,1);

    }
  1. 将数据导入数据库demo
 /*
     * 数据导入数据库
     * $name_table: 表名
     * $field_table: 表字段
     * $data_table:  表数据
     * $delOutTable: 是否删除已存在的同名表,default=>0,0 =>不删除,1=>删除
     * */
    private function inputDb( $name_table, $field_table, $data_table, $delOutTable=0){
        //检测数据表是否存在
        $isTable = $this->isExist($name_table);

        //删除已存在的表
        if($isTable &&  $delOutTable){
            $sql_del = "drop table ".$name_table;
            try {
                Db::connect(config('outfaceDb'))->execute($sql_del);
            }catch (\Exception $e){
                $msg = ["status"=>0 , 'msg'=>'删除旧表'.$name_table.'失败'];
                exit(json_encode($msg));
            }
            $isTable = $this->isExist($name_table);
        }

        //根据字段创建数据表
        if(!$isTable){
            $sql = "CREATE TABLE ".$name_table." (";
            foreach ($field_table as $v){
                $sql .= $v." varchar(255),";
            }
            $sql = substr($sql,0,strlen($sql)-1);  //去掉多余的符号 ,
            $sql .= ");";
            try {
                Db::connect(config('outfaceDb'))->execute($sql);
            }catch (\Exception $e){
                $msg = ["status"=>0 , 'msg'=>'数据库表创建sql存在问题,请检查excel格式是否满足要求:
                1.每个记录数据都必须对应一个表头(默认为表格第三行) 
                2.表格前两行将被忽略,第三行为对应表字段 
                3. 数据表对应数据从第4行开始'];
                exit(json_encode($msg));
            }
        }
        //根据表名查询该表的所有表字段
        $res_field = $this->getFiledName($name_table);

        //数据字段匹配(匹配字段是否存在于数据表字段)
        $err = []; // 错误记录数组
        $insert_arr = []; //预插入数组
        foreach ($data_table as $key=>$value){
            $match_status = $this->matchField($res_field,$value);
            if ($match_status){
                array_push($insert_arr,$value);
            }else{
                $info = [];
                $info['msg'] = "与数据表字段未匹配成功";
                $info['data'] = $value;
                array_push($err,$info);
            }
        }

        if (count($err ) === 0){
            //插入数据
            $num = Db::connect(config('outfaceDb'))->table($name_table)->insertAll($insert_arr);
            $msg = ["status"=>1 , 'msg'=>'成功插入'.$num.'条数据。'];
            exit(json_encode($msg));
        }else{
            $err['status'] = 0;
            exit(json_encode($err));
        }

    }

    /*
     * 根据表名查询该表是否存在
     * $table: 表名
     * return: bool
     * */
    private function isExist($table){
        $isTable = Db::connect(config('outfaceDb'))->query('SHOW TABLES LIKE "'.$table.'";');
        if($isTable){
            //表存在
            return 1;
        }else{
            //表不存在
            return 0;
        }

    }

    /*
     * 根据表名查询该表的所有表字段
     * $table: 表名
     * return: array
     * */
    public function getFiledName($table){
        $filed_arr = [];
        try {
            $filed = Db::connect(config('outfaceDb'))->query('show columns from '.$table.';');
        }catch (\Exception $e){
            $msg = ["status"=>0 , 'msg'=>'数据库连接出错'];
            exit(json_encode($msg));
        }

        foreach ($filed as $key=>$value){
            $filed_arr[$value['Field']] = '';
        }
        return $filed_arr;
    }

    /*
     *数据字段匹配(匹配字段是否存在于数据表字段)
     *$table_field : 数据表字段
     *$face_data : 匹配字段
     * return: bool
     * */
    public function matchField($table_field, $face_data){
        foreach ($face_data as $face_key=>$face_value){
            $have = 0;
            foreach ($table_field as $table_key=>$table_value){

                if ($face_key === $table_key){
                    $have = 1;
                }
            }
            if ( !$have){
                return 0;
            }
        }
        return 1;
    }

3.tp5 数据库连接示例( 在config文件中配置):

 'outfaceDb'  => [
        // 数据库类型
        'type'        => 'mysql',
        // 服务器地址
        'hostname'    => '127.0.0.1',
        // 数据库名
        'database'    => 'site_interface',
        // 数据库用户名
        'username'    => 'root',
        'username'    => 'root',
        // 数据库密码
        'password'    => 'root',
        // 数据库编码默认采用utf8
        'charset'     => 'utf8',
        // 数据库表前缀
        'prefix'      => '',
    ],
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值