### ライブラリインストール
$ composer require maatwebsite/excel
app/config.php
'providers' => [
Maatwebsite\Excel\ExcelServiceProvider::class,
],
'aliases' => [
'Excel' => Maatwebsite\Excel\Facades\Excel::class,
],
$ php artisan vendor:publish –provider=”Maatwebsite\Excel\ExcelServiceProvider”
$ php artisan make:export Export
app/Exports/Export.php
namespace App\Exports;
// use Maatwebsite\Excel\Concerns\FromCollection;
use Illuminate\Contracts\View\View;
use Maatwebsite\Excel\Concerns\FromView;
class Export implements FromView
{
/**
* @return \Illuminate\Support\Collection
*/
// public function collection()
// {
// //
// }
private $view;
public function __contruct(View $view){
$this->view = $view;
}
public function view(): View {
return $this->view;
}
}
routing
Route::get('/export', [App\Http\Controllers\AdminController::class, 'export']);
controller
use App\Http\Requests\UserFormRequest;
use App\Exports\Export;
public function export(){
$users = User::get();
$view = view('admin.export', compact('users'));
return \Excel::download(new Export($view), 'users.xlsx');
}
export.blade.php
<table>
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>email</th>
</tr>
</thead>
<tbody>
@foreach ($users as $user)
<tr>
<td>{{$user->id}}</td>
<td>{{$user->name}}</td>
<td>{{$user->email}}</td>
</tr>
@endforeach
</tbody>
</table>
ほうほう、中々デキる、こやつ
