Laravel Excel

repository·3.1·Indexed 11 days ago

https://github.com/spartnernl/laravel-excel

A 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.

Tokens
4K
Snippets
18
Records
22
Agent score
81%

What's inside Laravel Excel

  1. Overview of Laravel Excel

    3.1
    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.
  2. Key features of Laravel Excel

    3.1

    Laravel 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.
  3. Mocking Excel operations with ExcelFake

    3.1

    When writing tests for Laravel Excel, you can use ExcelFake to mock the Excel facade. This allows you to verify that exports, imports, downloads, and queued jobs are being handled correctly without actually performing file system or queue operations.

    ExcelFake tracks 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');
  4. Configure the heading row formatter

    3.1

    The HeadingRowFormatter determines how heading row values are transformed during an import. You can set a global formatter using HeadingRowFormatter::default(), or rely on the excel.imports.heading_row.formatter configuration 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');
  5. Supported versions for Laravel Excel

    3.1

    The following version compatibility matrix applies to the current supported version (3.1):

    VersionLaravel VersionPhp VersionSupport
    3.1>=5.8 | <=13.x^7.2 | ^8.0New features

    Note: Versions 2.1 and 3.0 are no longer supported.

  6. Assert Excel imports

    3.1

    Use assertImported to 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;
    });
  7. Extend the heading row formatter with custom logic

    3.1

    You can define custom formatting logic for heading rows by using the extend method. This allows you to register a new formatter name associated with a callable (a function or method) that processes the heading value.

    When the custom formatter is called, it receives the heading $value and 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');
  8. Get the underlying SpreadsheetRow delegate

    3.1

    The getDelegate() method returns the underlying PhpOffice\PhpSpreadsheet\Worksheet\Row instance. This allows you to access low-level PhpSpreadsheet methods directly on the row object.

    $spreadsheetRow = $row->getDelegate();
  9. Check if a Row is empty

    3.1

    Use 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 to false).
    • $endColumn: An optional string specifying the last column to check (e.g., 'G').
    if ($row->isEmpty()) {
        // Handle empty row
    }
  10. Export files using the Excel facade

    3.1

    The Excel class 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 implements ShouldQueue.

    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 $export object implements ShouldQueue, it will automatically call queue() 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');