TP5.1excel导入数据库的代码?php excel如何导入数据库?

原创文章引自(https://www.ympfb.com/show-29-154-1.html)

在用之前必须
use think\PHPExcel;
并且这个是第三方类库,这个类库是直接用命令能后下载的
composer 命令:
composer require phpoffice/phpexcel

public function save(){
        //前台的form表单大家都会吧,我就不写了
        //设置文件上传的最大限制
        ini_set('memory_limit','1024M');
        //加载第三方类文件
        require_once "../extend/PHPExcel/PHPExcel.php";
        //防止乱码
        header("Content-type:text/html;charset=utf-8");
        //实例化主文件
        //接收前台传过来的execl文件
        $file = $_FILES['file'];
        //截取文件的后缀名,转化成小写
        $extension = strtolower(pathinfo($file['name'],PATHINFO_EXTENSION));
        if($extension == "xlsx"){
            //2007(相当于是打开接收的这个excel)
            $objReader =\PHPExcel_IOFactory::createReader('Excel2007');
        }else{
            //2003(相当于是打开接收的这个excel)
            $objReader = \PHPExcel_IOFactory::createReader('Excel5');
        }

        $objContent = $objReader -> load($file['tmp_name']);

        if ($objContent){
            $sheetContent = $objContent -> getSheet(0) -> toArray();
            //删除第一行标题
   //dump($sheetContent);die;
   //其实到这里就结束了,就已经得到excel表格的所有数据了,下面就是如何插入数据库的问题了 ,下面我的方法大家可以参考

   $len = count($sheetContent);
   //var_dump($len);exit;
   if($len == 1){
    echo "<script>alert('请不要拿空表格来骗我');window.history.back();</script>";
    exit();
   }

   for($i = 1;$i<$len; $i++){
    $data = [
     'id' => '',
     'phone' => $sheetContent[$i][0],
     'company_name' => $sheetContent[$i][1],
     'add_id' => $sheetContent[$i][2],
     'industry_id' => $sheetContent[$i][3],
     'data_name' => $sheetContent[$i][4],
     'data_address' => $sheetContent[$i][5],
     'data_class' => $sheetContent[$i][6],
     'data_set_up_date' => $sheetContent[$i][6],
     'create_time' => date('Y-m-d')
    ];
    //dump($data);die;
    $re = Db::name('data_decoration_company')->insert($data);
   }
            //var_dump($res);die;
if($re){
    echo "<script>alert('导入成功');window.history.back();      </script>";
    exit();
    $this->redirect('/')->remember();
}else{
    echo "<script>alert('导入失败了,慢点慢点@!@本电脑的脑子已经跟不上你的节奏了');window.history.back();</script>";
    exit();
    $this->redirect('/')->remember();
    }
}else{
    $this->error('请导入表格 !');
}
    }
``````php
本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 1

phpoffice/phpexcel早都被遗弃了,别来这里误导人,该用phpspreadsheet

2年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!