Laravel Excel
repository·3.1·Indexed 11 days ago
https://github.com/spartnernl/laravel-excelA powerful wrapper for PhpSpreadsheet that provides a Laravel-idiomatic way to handle Excel and CSV exports and imports. Version 3.1 supports Laravel >=5.8 | <=13.x and PHP ^7.2 | ^8.0. Key features include Collection and Blade view exports, high-performance chunked imports into Eloquent models, queued background processing, and a comprehensive ExcelFake utility for testing operations.
What's inside Laravel Excel
- Laravel Excel is an elegant Laravel wrapper around PhpSpreadsheet designed to simplify Excel and CSV exports and imports. It provides high-level abstractions to handle complex spreadsheet tasks within the Laravel ecosystem.
Key features of Laravel Excel
3.1Laravel Excel provides several high-performance features for handling spreadsheet data:
- Collection Exports: Easily export Laravel collections directly to Excel or CSV documents.
- High-Performance Exports: Export database queries with automatic chunking to manage memory. Large datasets can be exported via background queues.
- High-Performance Imports: Import workbooks and worksheets directly into Eloquent models using chunk reading and batch inserts. Large file imports can be queued chunk-by-chunk to run in the background.
- Blade View Exports: Create custom spreadsheet layouts by using HTML tables within Blade views and exporting them to Excel.
Mocking Excel operations with ExcelFake
3.1When writing tests for Laravel Excel, you can use
ExcelFaketo mock theExcelfacade. This allows you to verify that exports, imports, downloads, and queued jobs are being handled correctly without actually performing file system or queue operations.ExcelFaketracks all interactions and provides assertion methods to verify the state of your Excel operations.// Example of how you might use Excel::fake() in a test Excel::fake(); // Perform your logic... Excel::store(new MyExport, 'exports/data.xlsx'); // Assert the operation occurred Excel::assertStored('exports/data.xlsx');Configure the heading row formatter
3.1The
HeadingRowFormatterdetermines how heading row values are transformed during an import. You can set a global formatter usingHeadingRowFormatter::default(), or rely on theexcel.imports.heading_row.formatterconfiguration value.Available built-in formatters:
none: Returns the heading value exactly as it appears in the file.slug: Converts the heading value into a slug using underscores as separators (e.g., "First Name" becomes "first_name").
use Maatwebsite\ Excel\Imports\HeadingRowFormatter; // Set the formatter to 'none' globally HeadingRowFormatter::default('none'); // Or set it to 'slug' (default behavior) HeadingRowFormatter::default('slug');Supported versions for Laravel Excel
3.1The following version compatibility matrix applies to the current supported version (3.1):
Version Laravel Version Php Version Support 3.1 >=5.8 | <=13.x ^7.2 | ^8.0 New features Note: Versions 2.1 and 3.0 are no longer supported.
Get the current Row index
3.1The
getIndex()method returns the integer index of the current row within the spreadsheet.$index = $row->getIndex();Assert Excel imports
3.1Use
assertImportedto verify that a file was imported from a specific disk. You can provide a callback to inspect the import object.assertImported(string $filePath, $disk = null, $callback = null)Excel::assertImported('uploads/data.csv', 'local', function ($import) { return $import instanceof MyImport; });Extend the heading row formatter with custom logic
3.1You can define custom formatting logic for heading rows by using the
extendmethod. This allows you to register a new formatter name associated with acallable(a function or method) that processes the heading value.When the custom formatter is called, it receives the heading
$valueand its original$key.use Maatwebsite\Excel\Imports\HeadingRowFormatter; // Register a custom formatter named 'uppercase' HeadingRowFormatter::extend('uppercase', function ($value, $key) { return strtoupper($value); }); // Activate the custom formatter HeadingRowFormatter::default('uppercase');Assert Excel raw exports
3.1Use
assertExportedInRawto verify that an export was processed using therawmethod. The assertion checks for the existence of the export class name in the internal tracking.assertExportedInRaw(string $classname, $callback = null)Excel::assertExportedInRaw(MyExport::class);Get the underlying SpreadsheetRow delegate
3.1The
getDelegate()method returns the underlyingPhpOffice\PhpSpreadsheet\Worksheet\Rowinstance. This allows you to access low-level PhpSpreadsheet methods directly on the row object.$spreadsheetRow = $row->getDelegate();Check if a Row is empty
3.1Use the
isEmpty()method to determine if a row contains any data. This method filters out null values to check for actual content.Parameters:
$calculateFormulas: Whether to calculate formula results (defaults tofalse).$endColumn: An optional string specifying the last column to check (e.g.,'G').
if ($row->isEmpty()) { // Handle empty row }Export files using the Excel facade
3.1The
Excelclass provides several methods to export data. You can download a file directly to the user's browser, store it on a filesystem disk, or queue the export job if the export object implementsShouldQueue.Available Export Methods
download($export, $fileName, $writerType = null, $headers = []): Generates the file and returns a Laravel download response. It automatically cleans the output buffer to prevent corruption.store($export, $filePath, $diskName = null, $writerType = null, $diskOptions = [], $disk = null): Saves the exported file to a specific disk. If the$exportobject implementsShouldQueue, it will automatically callqueue()instead.queue($export, $filePath, $disk = null, $writerType = null, $diskOptions = []): Dispatches the export to a background queue.raw($export, $writerType): Returns the raw file contents as a string.
// Download an export Excel::download(new UsersExport, 'users.xlsx'); // Store an export on a disk Excel::store(new UsersExport, 'exports/users.xlsx', 's3'); // Queue an export (if UsersExport implements ShouldQueue) Excel::store(new UsersExport, 'exports/users.xlsx', 'local');