//前端---部分代码
    <form class="form-inline" style="margin-top: 20px" method="post" action="/admin/commerce/import" enctype="multipart/form-data" style="display:inline-block">
        <div class="form-group">
            <label for="commerce_file">选择文件</label>
            <input class="form-control input-sm" type="file" name="commerce_file">
        </div>
        <button type="submit" class="btn btn-info">数据导入按钮</button>
    </form>



  //后端---原生封装导入方法
    public function actionimport()
    {
        if(!$_FILES['commerce_file']['name'])
        {
            $this->success('请选择csv格式文件');
        }
        if($_FILES['commerce_file']['size'] >= '2097152')//2M
        {
            $this->success('文件不能超过2M');
        }
        //获取储存的临时文件名
        $csv_file = $_FILES['commerce_file']['tmp_name'];

        //打开文件获取可读权限
        $file = fopen($csv_file,"r");

        //输出文本中所有的行,直到文件结束为止
        while(! feof($file))
        {
            //函数从文件指针中读入一行并解析CSV 段
            $data_line = fgetcsv($file);

            if($data_line)
            {
                foreach($data_line as $k => $v)
                {
                    //指定文件从gbk编码转换,为utf-8编码
                    $data_line[$k] = iconv('gbk','utf-8',$v);
                }
                $data[] = $data_line;
            }
        }
        //关闭打开文件
        fclose($file);
        $first = $data[0];
        //设定表头标题名称
        $name = array('ID','名称');
        if($first)
        {
            foreach($first as $k => $v)
            {
                if($v != $name[$k])
                {
                    $this->success('文件格式错误,请查看文件格式核实');
                }
            }
        }
        if($data)
        {
            //删除第一行数据
            unset($data[0]);
            //统计插入数量
            $sum = 0;
            foreach($data as $v)
            {
                //插入数据方法自己根据框架定义
                $rs = Yii::app()->getDb()->createCommand()->insert('sdk_commerce', array(
                    'id' => $v[0],
                    'name' => $v[1]
                ));
                $sum += $rs;
            }
            $this->success('成功导入<font color=red><b>'.$sum.'</b></font>条数据','/admin/commerce/list/');
        }
    }

 

相关文章:

  • 2022-01-06
  • 2021-11-18
  • 2022-12-23
  • 2021-07-04
  • 2022-02-20
  • 2021-11-23
  • 2022-12-23
  • 2021-06-19
猜你喜欢
  • 2021-08-26
  • 2022-12-23
  • 2021-09-20
  • 2022-12-23
  • 2022-01-04
  • 2021-11-20
  • 2021-12-26
相关资源
相似解决方案