1.這是個我去公司之后曾經折磨我很久很久的功能查閱了很多資料但是功夫不負有心人在本人的不懈努力下還是實現了這個功能
(ps看不懂我下面說講述的可以參考這個laravel學院的官方文檔 https://xueyuanjun.com/post/2024.html)
官方主頁:https://laravel-excel.com/
1.1使用的時候先用composer安裝excel依賴
這里需要注意一下最好只用laravel5.0的框架然后使用excel2.0不然的話會報錯
第一個是默認安裝一般安裝最新版本,第二個是2.1版本
composer require maatwebsite/excel composer require maatwebsite/excel ~2.1
1.2同樣在config/app.php
中注冊門面到aliases
數組:
'Excel' => Maatwebsite\Excel\Facades\Excel::class,
1.3如果想要對Laravel Excel進行更多的自定義配置,執行如下Artisan命令:(ps:這個看情況選擇你需要的配置)
php artisan vendor:publish
上面的如果你不會執行的話就直接執行第二個
php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider"

namespace App\Http\Controllers; use App\Http\Controllers\Admin\ContentTypes\File; use App\Models\Win1; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Input; use Illuminate\Support\Facades\Schema; use Illuminate\Support\Facades\Storage; use Maatwebsite\Excel\Facades\Excel; use Illuminate\Routing\Controller; use Symfony\Component\CssSelector\Parser\Reader;
將數據導出excel功能代碼

public function index(Excel $excel){ //將數據庫中的信息轉化為excel文件內容 $data=Win1::with('hasManyWindow')->get(); foreach ($data as $key){ $export[]=array( 'id'=>$key['id'], 'window'=>$key['window'], // 數據表中的兩個字段 ); } $table_name='窗口名稱'; $excel::create($table_name,function ($excel)use($export){ $excel->sheet('Sheet1',function ($sheet)use($export){ $sheet->fromArray($export); }); })->store('xlsx')->export('xlsx'); }
將excel表中的數據通過視圖層按鈕導入數據庫

public function excelfile(Request $request) { //1.思路get傳輸過來的Excel文件地址 //2.循環讀取數據保存到數組 //3.循環數組保存到數據庫中 $flag=true; $file=$request->file('file'); if($file){ //得到文件的路徑 $realPath = $file->getRealPath(); //上傳文件的后綴. $entension = $file -> getClientOriginalExtension(); // 獲取上傳的文件緩存在tmp文件夾下的絕對路徑 $newpath=$file->getRealPath(); $tabl_name = date('YmdHis').mt_rand(100,999);//時間戳 if($flag==true){ Excel::load($realPath,function ($reader) use ($tabl_name){ //獲取excel的第幾張表 $reader = $reader->getSheet(0); //獲取表中的數據 $data = $reader->toArray(); for($row=0;$row<count($data);$row++){ //echo $data[$row]['0'].' '; DB::table('windowmessage')->insert(['id'=>$data[$row]['0'],'window'=>$data[$row]['1']]); } }); return '<script>alert("文件上傳成功");window.location.href="importexcel"</script>'; } }else{ return '<script>alert("文件為空上傳失敗!請重新上傳");window.location.href="importexcel"</script>'; } }
下面是blade模板中的代碼(ps:給自己看的)

<a href="{{url('excelExport')}}" id="href"><div id="btn" >下載Excel</div></a> {{--導入按鈕--}} <form style="display:none" action="{{url('excelfile')}}" method="post" enctype="multipart/form-data"> {{csrf_field()}} <input type="file" name="file" value=""> </form> <input type="submit" value="批量導入" id="tijiao" > <!-- 記得載入jquery文件 --> <script> $('#tijiao').click(function(){ $(this).prev('form').find('[name="file"]').trigger('click'); }); // 當表單文件有變化時執行提交動作 $('[name="file"]').change(function(){ if($(this).val()){ $('#tijiao').addClass('disabled' ); $(this).parent().submit(); } }); </script>