excel导入功能

1.上github下载PHPExcel,链接:https://github.com/PHPOffice/PHPExcel

2.下载解压后,将Classes改名为PHPExcel如图

3.将文件夹复制到项目内extend

4.html代码

<form method="post" action="/admin/pos/posImport" class="form-signin" enctype="multipart/form-data" role="form"  id="form" >
      <input name="excel" type="file" class="form-control excel_path">
      <input type="submit" value="导入Excel" class="btn btn-lg btn-primary btn-block">
</form>

 5.php代码

//上传excel文件
        $file = request()->file('excel');
        //将文件保存到public/uploads目录下面
        $info = $file->validate(['size'=>1048576,'ext'=>'xls,xlsx'])->move( './uploads');
        if($info){
            //获取上传到后台的文件名
            $fileName = $info->getSaveName();
            //获取文件路径
            $filePath = Env::get('root_path').'public'.DIRECTORY_SEPARATOR.'uploads'.DIRECTORY_SEPARATOR.$fileName;
            //获取文件后缀
            $suffix = $info->getExtension();
            //判断哪种类型
            if($suffix=="xlsx"){
                $reader = \PHPExcel_IOFactory::createReader('Excel2007');
            }else{
                $reader = PHPExcel_IOFactory::createReader('Excel5');
            }
        }else{
            $this->error('文件过大或格式不正确导致上传失败-_-!');
        }
        //载入excel文件
        $excel = $reader->load("$filePath",$encode = 'utf-8');
        //读取第一张表
        $sheet = $excel->getSheet(0);
        //获取总行数
        $row_num = $sheet->getHighestRow();
        //获取总列数
        $col_num = $sheet->getHighestColumn();
        $data = []; //数组形式获取表格数据
        for ($i = 2; $i <= $row_num; $i ++) {
            $data[$i]['code']  = $sheet->getCell("A".$i)->getValue();
            $data[$i]['last_code']  = substr($sheet->getCell("A".$i)->getValue(),-6);
            $time = date('Y-m-d H:i',\PHPExcel_Shared_Date::ExcelToPHP($sheet->getCell("B".$i)->getValue()));//将excel时间改成可读时间
            $data[$i]['time'] = strtotime($time);
            //将数据保存到数据库
        }
        $res = Db::name('pos_code')->insertAll($data);

 如此便可以导入表格了

原文: https://www.cnblogs.com/BearLee/p/10345764.html

posted @ 2019-07-16 16:39  study_php_java_C++  阅读(757)  评论(0编辑  收藏  举报