Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Fast Excel Laravel Package

rap2hpoutre/fast-excel

Fast, memory-efficient Excel/CSV/ODS import/export for Laravel using Spout. Export Eloquent models or collections to XLSX/CSV/ODS with custom column mapping, and download from controllers. Import files to collections, configure CSV options, or transform rows into DB inserts.

View on GitHub
Deep Wiki
Context7

Getting Started

Install via Composer:

composer require rap2hpoutre/fast-excel

First Use Case: Export a Laravel Eloquent collection to an Excel file:

use Rap2hpoutre\FastExcel\FastExcel;
use App\Models\User;

// Export all users to a file
(new FastExcel(User::all()))->export('users.xlsx');

Where to Look First:


Implementation Patterns

1. Basic Export/Import Workflows

Export a Model or Collection:

// Export Eloquent results
(new FastExcel(User::where('active', 1)->get()))->export('active_users.xlsx');

// Export a Collection
$users = collect([['name' => 'John'], ['name' => 'Jane']]);
(new FastExcel($users))->export('users.xlsx');

Download Directly in a Controller:

return (new FastExcel(Order::all()))->download('orders.xlsx');

Import a File:

$importedData = (new FastExcel)->import('data.xlsx');

2. Custom Column Mapping

Transform data before export:

(new FastExcel(User::all()))
    ->export('users.csv', function ($user) {
        return [
            'Full Name' => $user->first_name . ' ' . $user->last_name,
            'Email'     => strtolower($user->email),
        ];
    });

3. Chunked Exports for Large Datasets

Avoid memory issues with generators:

function largeUserGenerator() {
    foreach (User::cursor()->where('status', 'active') as $user) {
        yield $user;
    }
}

(new FastExcel(largeUserGenerator()))->export('large_export.xlsx');

4. Multi-Sheet Exports

Export multiple collections to separate sheets:

use Rap2hpoutre\FastExcel\SheetCollection;

$sheets = new SheetCollection([
    'Users'     => User::all(),
    'Invoices'  => Invoice::all(),
]);

(new FastExcel($sheets))->export('multi_sheet.xlsx');

5. CSV Customization

Configure CSV-specific settings:

$importedData = (new FastExcel)
    ->configureCsv(';', '"', 'gbk') // Delimiter, enclosure, encoding
    ->import('data.csv');

6. Styling Exports

Apply styles to headers/rows:

use OpenSpout\Common\Entity\Style\Style;

$headerStyle = (new Style())->setFontBold();
$rowStyle    = (new Style())->setBackgroundColor('EDEDED');

(new FastExcel(User::all()))
    ->headerStyle($headerStyle)
    ->rowsStyle($rowStyle)
    ->download('styled_export.xlsx');

7. Import with Database Sync

Directly insert imported data into the database:

(new FastExcel)->import('users.xlsx', function ($row) {
    return User::create([
        'name'  => $row['Name'],
        'email' => $row['Email'],
    ]);
});

8. Facade Usage (Controllers)

Add to config/app.php:

'FastExcel' => Rap2hpoutre\FastExcel\Facades\FastExcel::class,

Then use in controllers:

FastExcel::data(User::all())->export('users.xlsx');

9. Global Helper

Use fastexcel() anywhere in the app:

$users = fastexcel()->import('users.xlsx');
fastexcel($users)->export('processed_users.xlsx');

10. Integration with Queues

Offload large exports to a queue job:

// Job class
public function handle() {
    (new FastExcel(User::all()))->export(storage_path('app/large_export.xlsx'));
}

Gotchas and Tips

Pitfalls

  1. PHP Version Requirement:

    • FastExcel requires PHP 8+ (dropped PHP 7.1 support in v3.0.0).
    • Fix: Update your PHP version or use Laravel Excel if stuck on PHP 7.4.
  2. Memory Limits with Large Exports:

    • Even with chunking, very large exports (e.g., >10M rows) may hit PHP’s memory_limit.
    • Fix: Increase memory_limit in php.ini or process in smaller batches.
  3. CSV Encoding Issues:

    • Custom CSV encodings (e.g., gbk) may cause corruption if the file isn’t saved with the correct encoding.
    • Fix: Ensure the file is saved as UTF-8 or the specified encoding.
  4. Multi-Sheet Import Limitations:

    • importSheets() returns an array of collections, but sheet names are not preserved by default.
    • Fix: Use withSheetsNames() to retain sheet names:
      $sheets = (new FastExcel)->withSheetsNames()->importSheets('file.xlsx');
      
  5. Styling Limitations:

    • Only header and row-level styles are supported. Cell-level styling requires Spout directly.
    • Fix: Use Spout’s CellInterface for granular control if needed.
  6. Facade Limitations:

    • The facade does not support the constructor, so you must use data() to set the export source.
    • Fix: Stick to direct instantiation if you need constructor features (e.g., chunking).
  7. No Event Hooks:

    • Unlike Laravel Excel, FastExcel lacks row/column event hooks for custom logic.
    • Fix: Use middleware or decorate the FastExcel class to add hooks.

Debugging Tips

  1. Check File Paths:

    • Ensure paths in export()/import() are absolute or relative to the correct directory.
    • Tip: Use storage_path() for reliable paths:
      (new FastExcel(User::all()))->export(storage_path('app/exports/users.xlsx'));
      
  2. Validate Imported Data:

    • Log the imported collection to verify data integrity:
      $data = (new FastExcel)->import('file.xlsx');
      \Log::info('Imported data:', $data->toArray());
      
  3. Memory Usage:

    • Monitor memory with memory_get_usage():
      $start = memory_get_usage();
      (new FastExcel(User::all()))->export('users.xlsx');
      $end = memory_get_usage();
      \Log::info('Memory used:', $end - $start);
      
  4. CSV Delimiter Issues:

    • If CSV imports fail, test with a simple delimiter (e.g., ,) before customizing.
    • Tip: Use an online CSV validator to check file integrity.

Extension Points

  1. Custom Writers/Readers:

    • Extend Rap2hpoutre\FastExcel\FastExcel to add custom logic:
      class CustomFastExcel extends FastExcel {
          public function customMethod() { ... }
      }
      
  2. Add Event Hooks:

    • Decorate the class to inject hooks:
      $fastExcel = new FastExcel(User::all());
      $fastExcel->setEventDispatcher($dispatcher); // Hypothetical
      
  3. Support Additional Formats:

    • Leverage Spout’s underlying library to add support for other formats (e.g., xls).
  4. Batch Processing Middleware:

    • Create middleware to validate/transform data before export:
      $fastExcel = new FastExcel(User::all());
      $fastExcel->setTransformer(new MyTransformer());
      

Configuration Quirks

  1. Spout Configuration:

    • Spout’s default settings may not suit all environments (e.g., tempDir).
    • Fix: Configure Spout globally via config/spout.php (if using Laravel’s config publishing).
  2. Facade vs. Direct Usage:

    • The facade cannot use constructor arguments (e.g., chunking). Use direct instantiation for advanced features.
  3. Sheet Naming in Multi-Sheet Exports:

    • Sheet names in SheetCollection must be strings (not objects). Non-string keys are ignored.

Performance Tips

  1. Use Generators for Large Exports:

    • Always use yield for datasets >10K rows to avoid memory spikes.
  2. Disable Unused Features:

    • Skip styling if not needed to reduce overhead:
      (new FastExcel(User::all()))->export('users.xlsx'); // No styles
      
  3. Leverage CSV for Large Imports:

    • CSV is faster to parse than XLSX for large imports. Use:
      (new FastExcel)->
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony