Laravel Fast Excel is a package that significantly enhances the speed and performance of Excel file exports in Laravel applications. It provides a simple and efficient way to generate Excel files, leveraging the underlying PhpSpreadsheet
library while focusing on speed and low memory usage.
Installation
You can install the Laravel Fast Excel package using Composer:
1 |
composer require maatwebsite/excel |
Basic Usage
Exporting Data
- Creating an Export Class: First, you need to create an export class. You can generate an export class using the Artisan command:
bash
1php artisan make:export UsersExportThis command creates a file in the
App\Exports
directory. - Implementing the Export Class: In your export class, implement the
FromCollection
interface to specify the data you want to export. Here’s an example of an export class for users:php123456789101112namespace App\Exports;use App\Models\User;use Maatwebsite\Excel\Concerns\FromCollection;class UsersExport implements FromCollection{public function collection(){return User::all();}}3.Exporting the Data: You can then export your data to Excel format in a controller or any part of your application:php1234567use App\Exports\UsersExport;use Maatwebsite\Excel\Facades\Excel;public function export(){return Excel::download(new UsersExport, 'users.xlsx');}
Advanced Features
Chunking Data
For larger datasets, you might want to use chunking to reduce memory usage. You can implement the FromQuery
interface and utilize chunking as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
use Maatwebsite\Excel\Concerns\FromQuery; use Maatwebsite\Excel\Concerns\WithHeadings; class UsersExport implements FromQuery, WithHeadings { public function query() { return User::query(); } public function headings(): array { return [ 'ID', 'Name', 'Email', 'Created At', 'Updated At', ]; } } |
Exporting to Different Formats
Laravel Fast Excel allows you to export to multiple formats, such as CSV or HTML. You can specify the format when calling the download
method:
1 |
return Excel::download(new UsersExport, 'users.csv'); // For CSV export |
Example Output
Here’s an example of how the exported Excel file might look when using Laravel Fast Excel:
ID | Name | Created At | Updated At | |
---|---|---|---|---|
1 | John Doe | john@example.com | 2024-01-01 12:00:00 | 2024-01-01 12:00:00 |
2 | Jane Smith | jane@example.com | 2024-01-02 14:30:00 | 2024-01-02 14:30:00 |
… | … | … | … | … |
Conclusion
Laravel Fast Excel provides a robust and efficient way to handle Excel exports in your Laravel applications. Its simplicity and performance benefits make it an excellent choice for projects dealing with large datasets or requiring quick export capabilities.