//首先要使用composer 安装扩展库PHPexcel (首先要确定电脑上安装了composer)
命令:
composer require phpoffice/phpexcel
//引入Excel公共类
vendor("PHPExcel.Classes.PHPExcel");
vendor('PHPExcel.Classes.PHPExcel.IOFactory.PHPExcel_IOFactory');
vendor('PHPExcel.Classes.PHPExcel.Reader.Excel5');
$objPHPExcel = new \PHPExcel();
$file = request()->file('filename');
$info = $file->validate(['ext' => 'xlsx,xls,csv'])->move(ROOT_PATH . 'public' . DS . 'uploads/import');//上传验证后缀名,以及上传之后移动的地址
if($info){
$exclePath = $info->getSaveName(); //获取文件名
$file_name = ROOT_PATH . 'public' . DS . 'uploads/import' . DS . $exclePath; //上传文件的地址
$objReader =\PHPExcel_IOFactory::createReader('Excel5');
$obj_PHPExcel =$objReader->load($file_name, $encode = 'utf-8'); //加载文件内容,编码utf-8
$excel_array=$obj_PHPExcel->getsheet(0)->toArray(); //转换为数组格式
array_shift($excel_array); //删除第一个数组(标题);
$datas = [];
$data_errors = [];
//处理Excel导入时数据为空的情况
foreach($excel_array as $k=>$v) {
if(!empty($v[0] || $v[1] || $v[2])){
$excel_list[] = $v;
}
}
$cn=count($excel_list);
//循环遍历,组装数据进行入库
foreach ($excel_list as $k=>$v){
if(!empty($v[0]) && !empty($v[1])){
$wh['job_number'] = $v[0];
$wh['is_deleted'] = '1';
$res_info=db('member')->where($wh)->count();
if($res_info ==0){
$data=array(
'job_number'=>$v[0],
'user_name'=>$v[1],
'department'=>$v[2],
'create_id' =>$admin_id,
'create_time'=>date('Y-m-d H:i:s'),
);
$datas[] = $data;
}
}else{
$error_data=array(
'job_number'=>$v[0],
'user_name'=>$v[1],
'department'=>$v[2],
'create_id' =>$admin_id,
'create_time'=>date('Y-m-d H:i:s'),
);
$data_errors[] = $error_data;
}
}
$errors_data = count($data_errors);
$repetition = $cn-$errors_data;
$success=db('member')->insertAll($datas); //批量插入数据
if($success){
$cn_fail=count($data_errors);
$content = "批量新增抽奖参与者名单记录:".json_encode($data);
$this->writelog($admin_id,$content,'4');//4出席成员
$error=$cn-$success;
$error_all = $error-$cn_fail;
$data = array(
'code'=>1,
'message'=>"总{$cn}条,导入成功{$success}条,其中失败{$cn_fail}条,重复{$error_all}条",
'result'=>$data_errors,
);
return json($data);
}
return json(['code'=>1,'message'=>"总{$cn}条,导入成功0条,其中重复{$repetition}条,失败{$errors_data}条",'result'=>$data_errors]);
}else{
// 上传失败获取错误信息
return json(['code'=>2,'message'=>'导入失败','result'=>null]);
}