主要是编码问题 把上传的文件做如下处理
$file = $_FILES;
$excel_file_path = $file['file']['tmp_name'];
//文件内容转码
$content = file_get_contents($excel_file_path);
$fileType = mb_detect_encoding($content, array('UTF-8', 'GBK', 'LATIN1', 'BIG5'));//获取当前文本编码格
$res = Excel::load($excel_file_path, function ($reader) {
}, $fileType)->get()->toArray();
就能得到 想要的数组 然后存入数据库, 就完成了excel的导入功能
注意修改的配置excel.php'heading' => false//
'to_ascii' => true
导入的代码
前端
导入EXCEL添加学生
- <form action="/admin/student/import" method='post' enctype="multipart/form-data">
- <input id="fileId1" type="file" accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" name="file"/>
- <input type="submit" value="确认">
- </form>
- 后端代码如下
- public function import(Request $request){
- if(!$request->hasFile('file')){
- exit('上传文件为空!');
- }
- $file = $_FILES;
- $excel_file_path = $file['file']['tmp_name'];
- $res = [];
- Excel::load($excel_file_path, function($reader) use( &$res ) {
- $reader = $reader->getSheet(0);
- $res = $reader->toArray();
- });
- for($i = 1;$i<count($res);$i++){
- $check = Students::where('name',$res[$i][0])->where('title',$res[$i][4])->count();
- if($check){
- continue;
- }
- $stu = new Students;
- $stu->name = $res[$i][0];
- $stu->group = $res[$i][1];
- $stu->teacher = $res[$i][2];
- $stu->school = $res[$i][3];
- $stu->mobile = $res[$i][4];
- $stu->title = $res[$i][5];
- $stu->save();
- }
- return Redirect::to('/admin/student')->withSuccess("导入成功");
- }