Export Excel Dari HTML di Laravel

Cara export ke Excel dari view HTML di Laravel menggunakan library Laravel Excel

Link: https://laravel-excel.com/

Install library

composer require maatwebsite/excel

Buat file export baru dengan perintah make:export

php artisan make:export BarangExport
// app/Exports/BarangExport.php

use App\Models\Barang;
use Illuminate\Contracts\View\View;
use Maatwebsite\Excel\Concerns\FromView;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;

class BarangExport implements FromView, ShouldAutoSize
{
    public function view(): View
    {
        $barang = Barang::all();

        return view('excel', compact('barang'));
    }
}
  • ShouldAutoSize digunakan agar lebar cell di Excel nya menyesuaikan isinya (auto width)

Buat file blade baru resources/views/excel.blade.php

<table>
    <thead>
        <tr>
            <th>No</th>
            <th>Barcode</th>
            <th>Kode Barang</th>
            <th>Nama Barang</th>
            <th>Harga Jual</th>
            <th>Harga Beli</th>
            <th>Satuan</th>
        </tr>
    </thead>
    <tbody>
        @foreach ($barang as $row)
            <tr>
                <td>{{ $loop->iteration }}</td>
                <td>{{ $row->barcode }}</td>
                <td>{{ $row->kode }}</td>
                <td>{{ $row->nama }}</td>
                <td>{{ $row->harga_jual }}</td>
                <td>{{ $row->harga_beli }}</td>
                <td>{{ $row->satuan }}</td>
            </tr>
        @endforeach
    </tbody>
</table>

Di controller app/Http/Controllers/BarangController.php tambahkan fungsi baru

use App\Exports\BarangExport;
use Maatwebsite\Excel\Facades\Excel;

// ...

public function export()
{
    return Excel::download(new BarangExport, 'data-barang.xlsx');
}

Route nya

Route::get('/barang/export', [BarangController::class, 'export'])->name('barang.export');

Button export untuk di view atau di menu

<a href="{{ route('barang.export') }}" class="btn btn-success">Export Excel</a>