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 Excel import/export for Laravel powered by Spout. Quickly export Eloquent models or collections to XLSX/ODS/CSV, customize column mapping, and download from controllers. Import files to collections, configure CSV options, or persist rows directly to the database.

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

use Rap2hpoutre\FastExcel\Facades\FastExcel;

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

Where to Look First:


Implementation Patterns

1. Exporting Data

Basic Export (Eloquent/Collection)

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

// Export with custom column mapping
(new FastExcel(User::all()))->export('users.xlsx', function ($user) {
    return [
        'Full Name' => $user->first_name . ' ' . $user->last_name,
        'Email' => $user->email,
    ];
});

Download in Controller

public function exportUsers()
{
    return (new FastExcel(User::all()))
        ->headerStyle((new Style())->setFontBold())
        ->download('users.xlsx');
}

Export Large Datasets (Chunking)

function usersGenerator()
{
    foreach (User::cursor() as $user) {
        yield $user;
    }
}

(new FastExcel(usersGenerator()))->export('large_users.xlsx');

2. Importing Data

Basic Import (CSV/XLSX)

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

Import with CSV Configuration

$rows = (new FastExcel)
    ->configureCsv(';', '"', 'gbk')
    ->import('data.csv');

Direct DB Insert on Import

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

3. Multi-Sheet Exports/Imports

Export Multiple Sheets

use Rap2hpoutre\FastExcel\SheetCollection;

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

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

Import Specific Sheet

$users = (new FastExcel)->sheet(1)->import('multi_sheet.xlsx');

Import All Sheets with Names

$sheets = (new FastExcel)->withSheetsNames()->importSheets('multi_sheet.xlsx');

4. Styling and Formatting

Header/Row Styling

use OpenSpout\Common\Entity\Style\Style;

$headerStyle = (new Style())->setFontBold()->setBackgroundColor('DDDDDD');
$rowStyle = (new Style())->setFontSize(12);

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

CSV Formatting

(new FastExcel)->configureCsv(',', "'", 'utf-8')->import('data.csv');

5. Facade and Helper Usage

Facade (Recommended for Clarity)

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

Global Helper (Quick Access)

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

6. Integration with Laravel Features

API Endpoint for Dynamic Exports

Route::get('/export/{type}', function ($type) {
    $data = match ($type) {
        'users' => User::all(),
        'invoices' => Invoice::where('status', 'paid')->get(),
        default => throw new \Exception('Invalid type'),
    };
    return (new FastExcel($data))->download("{$type}.xlsx");
});

Queued Exports (For Large Datasets)

// Dispatch a job for large exports
ExportUsersJob::dispatch();

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

7. Testing Exports/Imports

Unit Test for Export

public function test_export_users()
{
    $users = User::factory()->count(3)->create();
    $file = tempnam(sys_get_temp_dir(), 'test_');
    (new FastExcel($users))->export($file);

    $this->assertFileExists($file);
    unlink($file);
}

Unit Test for Import

public function test_import_users()
{
    $file = tempnam(sys_get_temp_dir(), 'test_');
    (new FastExcel)->export($file, function () {
        return [
            ['name' => 'John', 'email' => 'john@example.com'],
            ['name' => 'Jane', 'email' => 'jane@example.com'],
        ];
    });

    $imported = (new FastExcel)->import($file);
    $this->assertCount(2, $imported);
    unlink($file);
}

Gotchas and Tips

Pitfalls

  1. Memory Limits with Large Datasets

    • Issue: Exporting >100K rows may hit memory_limit.
    • Fix: Use chunking with cursor() or yield:
      (new FastExcel(User::cursor()))->export('large_file.xlsx');
      
  2. CSV Encoding Issues

    • Issue: Special characters (e.g., é, ü) may corrupt in CSV.
    • Fix: Explicitly set encoding:
      (new FastExcel)->configureCsv(',', '"', 'utf-8')->import('file.csv');
      
  3. Sheet Name Limitations

    • Issue: Excel sheet names cannot exceed 31 characters.
    • Fix: Truncate or sanitize names:
      $sheetName = substr($name, 0, 30);
      
  4. Facade vs. Class Instantiation

    • Issue: Facade (FastExcel::data()) does not support constructor options (e.g., configureCsv).
    • Fix: Use class instantiation for advanced config:
      (new FastExcel)->configureCsv(';', '"', 'gbk')->import('file.csv');
      
  5. PHP 8+ Requirement

    • Issue: FastExcel drops PHP 7.1 support (v3.0.0+).
    • Fix: Upgrade PHP or use an older version (v2.x).
  6. Large File Downloads

    • Issue: Browser timeouts for >50MB files.
    • Fix: Use chunked downloads or background jobs:
      return response()->streamDownload(function () {
          $excel = new FastExcel(User::cursor());
          $excel->export('large_file.xlsx');
      }, 'large_file.xlsx');
      
  7. Multi-Byte Character Truncation

    • Issue: Long Unicode strings (e.g., Japanese/Korean) may truncate.
    • Fix: Adjust column width dynamically:
      $excel->setColumnWidths([1 => 50]); // Set column B width to 50 chars
      

Debugging Tips

  1. Check File Permissions

    • Ensure the storage/app directory is writable:
      chmod -R 775 storage/app
      
  2. Validate CSV Delimiters

    • Test with a small CSV to confirm delimiters/enclosures:
      (new FastExcel)->configureCsv('|', '"', 'utf-8')->import('test.csv');
      
  3. Log Import Errors

    • Wrap imports in a try-catch to log malformed rows:
      try {
          $rows = (new FastExcel)->import('data.xlsx');
      } catch (\Exception $e) {
          Log::error("Import failed: " . $e->getMessage());
      }
      
  4. Verify Sheet Indexes

    • Excel sheets are 1-indexed (first sheet = 1):
      $sheet = (new FastExcel)->sheet(1)->import('file.xlsx');
      
  5. Test with Minimal Data

    • Start with 1–2 rows to isolate issues before scaling.

Extension Points

  1. Custom Writers/Readers
    • Extend Rap2hpoutre\FastExcel\FastExcel to add custom Spout writers:
      class CustomExcel extends FastExcel
      {
          public function __construct()
          {
              parent::__construct
      
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport