视图:
<form method="post" action="{:url('emp/addexcel')}" enctype="multipart/form-data"> <input name="file_stu" type="file" > <button class="btn btn-sm btn-primary ">导入</button> </form>
控制器:
public function addExcel() { if (!empty($_FILES['file_stu']['name'])) { //获取表单上传文件 vendor("PHPExcel.PHPExcel"); //方法一 $objPHPExcel = new \PHPExcel(); $file = request()->file('file_stu'); $info = $file->validate(['size' => 15678, 'ext' => 'xlsx,xls,csv'])->move(ROOT_PATH . 'public' . DS . 'Excel'); if (!$info) { // 上传错误提示错误信息 $this->error($upload->getError()); } else { $exclePath = $info->getSaveName(); //获取文件名 $file_name = ROOT_PATH . 'public' . DS . 'Excel' . DS . $exclePath; //上传文件的地址 $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 = []; $i = 0; foreach ($excel_array as $k => $v) { $data[$k]['realname'] = $v[0]; $data[$k]['d_id'] = $v[1]; $data[$k]['username'] = 'employee'; $data[$k]['password'] = '111111'; $data[$k]['r_id'] = 4; $data[$k]['statu'] = 0; $data[$k]['addtime'] = date('Y-m-d h:m:s', time()); $i++; } $success = Db::table('user')->insertAll($data); //批量插入数据 //$i= $error = $i - $success; // echo "总{$i}条,成功{$success}条,失败{$error}条。"; } $this->success('导入数据库' . $success . '条,成功。' . $error . '失败', 'emp/list'); } else { $this->error('(⊙o⊙)~没传数据就导入'); } }