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

Laravel Excel Laravel Package

cyber-duck/laravel-excel

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require cyber-duck/laravel-excel
    
    • Laravel 5.5+: No additional config needed (auto-discovery).
    • Laravel 4.x/5.0-5.4: Register Cyberduck\LaravelExcel\ExcelServiceProvider in config/app.php.
    • Laravel 5.5+: Use Cyberduck\LaravelExcel\ExcelLegacyServiceProvider if needed.
  2. First Export:

    use Cyberduck\LaravelExcel\Facades\Excel;
    
    // Export a collection to Excel
    $users = User::all();
    Excel::export($users, 'users.xlsx');
    
    • Output: File users.xlsx saved to storage/app/exports/.
  3. First Import:

    $file = Excel::import('path/to/file.xlsx');
    // $file is now a Collection of arrays (raw Excel data)
    

First Use Case: Export Eloquent Data

// Export with custom filename and path
Excel::export(User::where('active', 1)->get(), 'active_users.xlsx', 'exports');

// Export with custom column mapping
Excel::export(
    User::all(),
    'users.xlsx',
    null, // No custom path
    ['id', 'name', 'email'] // Columns to include
);

Implementation Patterns

1. Export Workflows

Basic Export

// Export a collection to a file
Excel::export($collection, 'filename.xlsx');

Chunked Exports (Large Datasets)

// Process in chunks to avoid memory issues
Excel::chunkExport(User::query(), 'large_users.xlsx', function ($chunk) {
    // Customize each chunk (e.g., format data)
    return $chunk->map(function ($user) {
        return [
            'id' => $user->id,
            'name' => strtoupper($user->name),
        ];
    });
});

Custom Headers and Styling

Excel::export(
    User::all(),
    'styled_users.xlsx',
    null,
    null,
    function ($writer) {
        $writer->getStyle()->getFont()->setBold(true); // Bold headers
        $writer->getStyle()->getFont()->setSize(12);
    }
);

2. Import Workflows

Basic Import

$file = Excel::import('path/to/file.xlsx');
foreach ($file as $row) {
    User::create($row); // Assuming $row matches User model
}

Validate and Process Rows

$file = Excel::import('path/to/file.xlsx');
$file->each(function ($row) {
    if (empty($row['email'])) {
        throw new \Exception("Row missing email: " . print_r($row, true));
    }
    User::create($row);
});

Import with Custom Mapping

$file = Excel::import('path/to/file.xlsx');
$file->each(function ($row) {
    User::create([
        'name' => $row['full_name'],
        'email' => $row['user_email'],
    ]);
});

3. Integration with Controllers

Export Endpoint

public function exportUsers(Request $request)
{
    return Excel::export(
        User::where('active', $request->active)->get(),
        'users_' . now()->format('Y-m-d') . '.xlsx'
    );
}

Import Endpoint

public function importUsers(Request $request)
{
    $file = $request->file('file');
    $data = Excel::import($file->path());

    foreach ($data as $row) {
        User::create($row);
    }

    return back()->with('success', 'Users imported!');
}

4. Queueing Exports (Laravel Queues)

// Dispatch a job for large exports
ExcelExportJob::dispatch(User::all(), 'queued_users.xlsx');

// Job class
class ExcelExportJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable;

    public function handle()
    {
        Excel::export($this->users, $this->filename);
    }
}

Gotchas and Tips

Pitfalls

  1. Memory Limits:

    • Large datasets (>10,000 rows) may hit memory limits. Use chunkExport() or queue the job.
    • Fix: Increase memory_limit in php.ini or process in chunks.
  2. File Paths:

    • Files are saved to storage/app/exports/ by default. Ensure this directory is writable.
    • Fix: Use absolute paths or configure a custom export path in the service provider.
  3. CSV Encoding Issues:

    • CSV exports may have encoding problems with special characters (e.g., é, ü).
    • Fix: Explicitly set encoding:
      Excel::export($users, 'users.csv', null, null, null, 'UTF-8');
      
  4. Legacy Laravel Support:

    • The package supports Laravel 4.x but may lack features from newer versions (e.g., no auto-discovery).
    • Tip: Prefer Laravel 5.5+ for active development.

Debugging Tips

  1. Check Raw Data:

    • Inspect the raw Excel data before processing:
      $rawData = Excel::import('file.xlsx');
      dd($rawData->toArray());
      
  2. Validate Headers:

    • Ensure column headers in the Excel file match your model/array keys. Use snake_case for consistency:
      // Excel header: "user_name" → Model field: "name"
      $file->each(function ($row) {
          User::create(['name' => $row['user_name']]);
      });
      
  3. Log Errors:

    • Wrap imports in try-catch to log issues:
      try {
          Excel::import('file.xlsx')->each(...);
      } catch (\Exception $e) {
          Log::error("Excel import failed: " . $e->getMessage());
      }
      

Extension Points

  1. Custom Writers:

    • Extend Cyberduck\LaravelExcel\Writer to add custom formatting:
      class CustomWriter extends \Cyberduck\LaravelExcel\Writer
      {
          public function __construct()
          {
              parent::__construct();
              $this->getStyle()->getFont()->setColor(new \PhpOffice\PhpSpreadsheet\Style\Color\Color('FF0000'));
          }
      }
      
    • Use it in exports:
      Excel::export($users, 'custom.xlsx', null, null, function ($writer) {
          $writer = new CustomWriter();
      });
      
  2. Pre-Import Validation:

    • Add validation before processing:
      $file = Excel::import('file.xlsx');
      $validator = Validator::make($file->toArray(), [
          '*.email' => 'required|email',
      ]);
      if ($validator->fails()) {
          throw new \Exception("Validation errors: " . $validator->errors());
      }
      
  3. Batch Processing:

    • Use Laravel's chunk() for database operations during import:
      $file = Excel::import('file.xlsx');
      $file->chunk(100)->each(function ($chunk) {
          User::insert($chunk->toArray());
      });
      

Performance Tips

  1. Disable Events for Bulk Imports:

    • Temporarily disable model events to speed up imports:
      User::withoutEvents(function () {
          $file->each(function ($row) {
              User::create($row);
          });
      });
      
  2. Use insert() Instead of create():

    • For bulk inserts, use insert() to avoid mass assignment checks:
      $file->each(function ($chunk) {
          User::insert($chunk->toArray());
      });
      
  3. Optimize Queries:

    • Avoid N+1 queries in exports by eager loading:
      Excel::export(User::with('posts')->get(), 'users_with_posts.xlsx');
      
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope