TP框架实现excel数据导入数据库

时间:2022-10-16 23:27:27

新手在项目中遇到的大批量Excel数据入库问题自己摸索出来的解决方法,分享一下,如果有问题欢迎留言讨论~


1、使用composer安装phpExcel (composer安装方法→点我

composer require phpoffice/phpexcel

2、引入相关类
use PHPExcel_IOFactory;
use PHPExcel;
3、后台处理入库操作
public function domysql()
    {

        $grade = input('grade');        //获取数据等级
        $file = request()->file('files');      //获取上传的文件
        $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');     //移动到指定目录

        //上传文件成功进行入库操作
        if($info){            
            //获取文件名称
            $exclePath = $info->getSaveName();  //获取文件名
            $file_name = ROOT_PATH . 'public' . DS . 'uploads' . DS . $exclePath;   //上传文件的地址

            //调用插件
            vendor('PHPExcel');
            vendor('PHPExcel.IOFactory');
            vendor('PHPExcel.Reader.Excel5');

            //实例化PHPExcel类
            $PHPExcel = new PHPExcel();
            $objReader =\PHPExcel_IOFactory::createReader('Excel2007');
            $obj_PHPExcel =$objReader->load($file_name, $encode = 'utf-8');  //加载文件内容,编码utf-8
            $excel_array=$obj_PHPExcel->getsheet(0)->toArray();   //转换为数组格式
            array_shift($excel_array);  //删除第一个数组(标题);
            $data = []; //准备一个数组容器用来根据数据库字段重构数组
            foreach ($excel_array as $key => $value) {                
                $data[$key]['name'] = preg_replace('/\s+/', '', $value['0']);    //正则去除多余空白字符
                $data[$key]['content'] = preg_replace('/\s+/', '', $value['1']);
                $data[$key]['control'] = preg_replace('/\s+/', '', $value['2']);
                $data[$key]['method'] = preg_replace('/\s+/', '', $value['3']);
                $data[$key]['recommend'] = preg_replace('/\s+/', '', $value['4']);
                $data[$key]['standard'] = preg_replace('/\s+/', '', $value['5']);
                $data[$key]['result'] = preg_replace('/\s+/', '', $value['6']);
                $data[$key]['accord'] = preg_replace('/\s+/', '', $value['7']);
                $data[$key]['remarks'] = preg_replace('/\s+/', '', $value['8']);
            }
            Db::name($grade)->insertAll($data); //批量插入数据
            $this->success('新增成功', 'index/index/excel');
        }else{
            $this->error('新增失败');
        }

    }
4、前台上传Excel文件页面
<!DOCTYPE html>
<html>
  <head>
    <title>测评项入库</title>
    <meta charset="UTF-8">
  </head>
  <body>
    <form id="upload" action="{:url('index/index/domysql')}" method="post" enctype="multipart/form-data">
      选择需要导入数据的等级:
      <select name="grade">
        <option value="s2a2g2">s2a2g2</option>
        <option value="s2a3g3">s2a3g3</option>
        <option value="s3a2g3">s3a2g3</option>
        <option value="s3a3g3">s3a3g3</option>
      </select>
      <br>
      <label for="file">上传文件:</label>
      
      <input type="file" name="files" id="file"><br />
      <input type="submit" name="submit" value="上传" />
    </form>
  </body>
</html>