laravel Excel匯出
阿新 • • 發佈:2018-12-25
安裝 maatwebsite/excel
blade模板
<p> <button onclick="scoreExcel()">匯出列表</button> </p> <table border="1" cellspacing="0"> <tr> <th>姓名</th> <th>分數</th> <th>科目</th> <th>時間</th> </tr> @foreach($lists as $value) <tr> <td>{{$value -> name}}</td> <td>{{$value -> score}}</td> <td>{{$value -> subject}}</td> <td>{{$value -> updated_at}}</td> </tr> @endforeach </table> <script> function scoreExcel() { window.location.href = 'scoreExcel' } </script>
控制器
// 匯出 public function scoreExcel() { DB::setFetchMode(PDO::FETCH_ASSOC); $arr = DB::table('test')->get(); $data = [ [ '姓名', '分數', '科目', '時間' ] ]; for ($i=1; $i < count($arr); $i++) { $data[$i] = [ $arr[$i]['name'], $arr[$i]['score'], $arr[$i]['subject'], $arr[$i]['updated_at'], ]; } Excel::create(iconv('UTF-8', 'GBK', '成績單'), function ($excel) use ($data) { $excel->sheet('recored', function ($sheet) use ($data) { $sheet->rows($data); }); })->export('xls'); }
$arr 資料結構