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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM