DEV Community

Cover image for Laravel Export and download Excel File
ashrakt
ashrakt

Posted on • Edited on

Laravel Export and download Excel File

1: Install maatwebsite/excel Package :

composer require maatwebsite/excel

2: php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider" --tag=config

3: php artisan make:export UsersExport --model=User

4:


<?php

namespace App\Exports;

use App\Models\User;
use Maatwebsite\Excel\Concerns\WithStyles;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithColumnWidths;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use Maatwebsite\Excel\Concerns\WithMapping;


class UsersExport implements FromCollection, WithHeadings, WithStyles  ,WithMapping ,WithColumnWidths
{

    public function collection()
    {
        return User::select("id", "name", "email")->get();

    }


 public function map($user): array
    {   
        return [
            $user->id,
            $user->name,
            $user->email,
        ];
    }


    public function headings(): array
    {
        return ["ID", "Name", "Email"];
    }




     public function columnWidths(): array
    {
        return [
            'A' => 5, 
            'B' => 5,
            'C' => 12, 
        ];
    }


    public function styles(Worksheet $sheet)
    {
        return [
            // Apply styles to the first row (headers)
            1 => [
                'font' => [
                    'bold' => true,
                    'color' => ['rgb' => '80000F'],
                    'size' => 12,
                ],
                'fill' => [
                    'fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID,
                    'startColor' => ['rgb' => 'EFE1E3'],
                ],
            ],
        ];
    }
}


Enter fullscreen mode Exit fullscreen mode

5: Create Controller

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
use App\Models\User;
use App\Exports\UsersExport;
use Carbon\Carbon;
use Illuminate\Support\Facades\Response;


class UserController extends Controller
{

 public function downloadUser()
    {
        $currentDate = Carbon::now()->format('Y-m-d'); 

        $fileName = 'users_' . $currentDate . '.xlsx';

        Excel::store(new UsersExport, 'exports/' . $fileName);

        $filePath = storage_path('app/exports/' . $fileName);

        if (file_exists($filePath)) {

             $headers = array('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');

        return Response::download( $filePath, $fileName , $headers)->deleteFileAfterSend(true);

         }
    }
}
Enter fullscreen mode Exit fullscreen mode

Image description

Top comments (0)