php laravel 5.1 使用excel 插件实现导入导出

1、数据库如下:

2、前台页面:

<form action="/excel/import" method='post' enctype="multipart/form-data">
<input type="hidden" name="_token" value="{{ csrf_token() }}" />
<input id="fileId1" type="file" accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" name="file"/>
<input type="submit" value="确认">
</form>
3、路由:
Route::get('admin/exceladd','admin\ExcelController@index');
Route::get('excel/export','admin\ExcelController@export');
Route::post('excel/import','admin\ExcelController@import');
4、controller:
public  function export(){
$student = DB::table('student')->get();
$student =json_encode($student,true);
$student =json_decode($student,true);
Array_unshift($student,['id','申请人','申请产品名称','申请理由','联系人1','联系人2','联系人3']);
Excel::create(iconv('UTF-8', 'GBK', '学生成绩').date('Y-m-d-H-i-s'),function($excel) use ($student){
$excel->sheet('score', function($sheet) use ($student){
$sheet->rows($student);
});
})->store('xls')->export('xls');
}

public function import(Request $request)
{
$file = $request->file('file');
$originalName = $file->getClientOriginalName(); // 文件原名
$ext = $file->getClientOriginalExtension(); // 扩展名
$realPath = $file->getRealPath(); //临时文件的绝对路径
$type = $file->getClientMimeType();
$filename = date('Y-m-d-H-i-s') . '-' . uniqid() . '.' . $ext;
$bool = Storage::disk('uploads')->put($filename, file_get_contents($realPath));
$filePath = 'storage/app/uploads/'.iconv('UTF-8', 'GBK', $filename);
Excel::load($filePath,function ($reader){
$reader = $reader->getSheet(0);
$data = $reader->toArray();
for($i=1;$i<count($data);$i++){
$student = array(
'num'=>$data[$i][0],
'name'=>$data[$i][1],
'score'=>$data[$i][2],
'remark'=>$data[$i][3],
);
$res=Student::forceCreate($student);
echo '成功';
}
});

}
记得引入命名空间和modle

 

posted @ 2018-09-03 17:54  Boser1u  阅读(1092)  评论(1编辑  收藏  举报