Cara Mudah Export Excel Pada Laravel
- Maulana Saputra
- https://docs.laravel-excel.com/3.1/exports/from-view.html
1. Instalasi
Di sini perlu untuk menginstall beberapa kebutuhan package dan beberapa yang berhubungan dengan PhpSpreadsheet.
composer require maatwebsite/excel
Registrasi pada ServiceProvider config/app.php .
'providers' => [
/*
* Package Service Providers...
*/
Maatwebsite\Excel\ExcelServiceProvider::class,
]
Dan juga pada bagian bawah.
'aliases' => [
...
'Excel' => Maatwebsite\Excel\Facades\Excel::class,
]
Publish pada config dengan menjalankan perintah ini.
php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider" --tag=config
2. Membuat Export Class
Pada langkah ini buat export class untuk mengexport excel.
php artisan make:export DeliveryOrderDetailExport
Kemudian pada app\Exports\DeliveryOrderDetailExport.php ubah seperti ini.
<?php
namespace App\Exports;
use Maatwebsite\Excel\Concerns\FromCollection;
use Illuminate\Contracts\View\View;
use Maatwebsite\Excel\Concerns\FromView;
class DeliveryOrderDetailExport implements FromView
{
public function __construct($data)
{
$this->data = $data;
}
/**
* @return \Illuminate\Support\Collection
*/
public function collection()
{}
public function view(): View
{
return view('exports.delivery-order-detail-export')->with('data', $this->data);
}
}
3. Membuat Blade View
Pada langkah ini untuk menulis excel yang akan kita buat.
Kemudian pada resources\views\exports\delivery-order-detail-export.blade.php
<table>
<thead>
<tr>
<th>No</th>
<th>Nama Supplier</th>
<th>No DO</th>
<th>Status</th>
</tr>
</thead>
<tbody>
@foreach($data as $row)
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
4. Memanggil Export Excel Controller
Pada langkah ini kita akan membuat perintah untuk mengexport excel pada controller.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Excel;
use App\Exports\DeliveryOrderDetailExport;
class DeliveryOrderController extends Controller
{
public function export()
{
$data = [
[
'no' => 1,
'name' => 'PT Maju Mundur',
'do' => 'DO-01',
'status' => 'aktif',
],
[
'no' => 2,
'name' => 'PT Bintang Kejora',
'do' => 'DO-02',
'status' => 'aktif',
],
];
return Excel::download(new DeliveryOrderDetailExport($data), 'delivery-order-detail-' . $id . '.xlsx');
}
}
Sekian untuk kali ini semoga bermanfaat :D untuk lebih lanjut bisa kunjungi link tersebut.