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

Phpspreadsheet Laravel Package

phpoffice/phpspreadsheet

PhpSpreadsheet is a pure PHP library to read and write spreadsheet formats like Excel and LibreOffice Calc. Create, edit, and export workbooks (XLSX, XLS, ODS, CSV, etc.) with a rich API for cells, formulas, styles, and more.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require phpoffice/phpspreadsheet
    

    Ensure your composer.json meets PHP 8.1+ requirements.

  2. First Use Case: Load and read an Excel file:

    use PhpOffice\PhpSpreadsheet\IOFactory;
    
    $spreadsheet = IOFactory::load('path/to/file.xlsx');
    $worksheet = $spreadsheet->getActiveSheet();
    $cellValue = $worksheet->getCell('A1')->getValue();
    
  3. Where to Look First:


Implementation Patterns

1. Reading Data Efficiently

  • Avoid toArray() for Large Files: Use iterators or cell-by-cell access to minimize memory:
    foreach ($worksheet->getRowIterator() as $row) {
        foreach ($row->getCellIterator() as $cell) {
            $value = $cell->getValue();
        }
    }
    
  • Batch Processing: Process chunks of rows to balance memory and performance:
    $highestRow = $worksheet->getHighestRow();
    $batchSize = 1000;
    for ($row = 1; $row <= $highestRow; $row += $batchSize) {
        $batch = $worksheet->rangeToArray(
            'A' . $row,
            'Z' . min($row + $batchSize - 1, $highestRow),
            true,
            false
        );
        // Process $batch
    }
    

2. Writing Data

  • Dynamic Worksheets: Create and populate worksheets dynamically:
    $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
    $worksheet = $spreadsheet->createSheet();
    $worksheet->setTitle('Dynamic Data');
    $worksheet->fromArray($dataArray, null, 'A1');
    
  • Styling: Apply styles conditionally:
    $style = $worksheet->getStyle('A1:A10');
    $style->getFont()->setBold(true);
    $style->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
    

3. Handling Formulas and Dates

  • Calculate Formulas: Enable formula calculation before reading:
    $spreadsheet->setStrictReading(true); // Calculate all formulas
    $value = $worksheet->getCell('B2')->getValue();
    
  • Date/Time Handling: Use getFormattedValue() for human-readable dates:
    $dateValue = $worksheet->getCell('C3')->getFormattedValue();
    

4. Integration with Laravel

  • File Uploads: Handle Excel uploads via Laravel's request system:
    $file = request()->file('excel_file');
    $spreadsheet = IOFactory::load($file->getPathname());
    
  • Queue Jobs: Offload heavy processing to queues:
    ProcessExcelJob::dispatch($spreadsheet, $userId)->onQueue('excel');
    

5. Exporting to PDF

  • Use PhpSpreadsheet + Dompdf/mPDF:
    $writer = IOFactory::createWriter($spreadsheet, 'Html');
    $html = $writer->save('php://output');
    $pdf = PDF::loadHTML($html)->setOption('isHtml5ParserEnabled', true);
    return $pdf->stream('report.pdf');
    

Gotchas and Tips

Pitfalls

  1. Memory Overhead:

    • toArray() loads the entire worksheet into memory. For large files (>100K rows), use iterators or batch processing.
    • Fix: Use getRowIterator() or rangeToArray() with limits.
  2. Empty Rows/Cells:

    • toArray() includes empty rows as null arrays. Filter manually:
      $nonEmptyRows = array_filter($dataArray, fn($row) => !empty(array_filter($row)));
      
  3. Merged Cells:

    • Merged cells may return unexpected values. Use getMergeCells() to check:
      if ($worksheet->getMergeCells()) {
          $mergedCells = $worksheet->getMergeCells();
          // Handle merged ranges
      }
      
  4. Formula Debugging:

    • Formulas may fail silently. Enable strict reading:
      $spreadsheet->setStrictReading(true);
      
    • Check for circular references or invalid syntax.
  5. Time Zones/Dates:

    • Excel dates are Unix timestamps. Use getDateTimeValue() for accurate parsing:
      $date = $worksheet->getCell('D5')->getDateTimeValue();
      

Debugging Tips

  • Log Cell Values:
    $worksheet->getCell('A1')->setValue('=SUM(B1:C1)');
    $worksheet->getCell('A1')->getCalculator()->setCreatePhpDoc(false); // Disable doc generation
    
  • Validate Formulas: Use getFormula() to inspect formulas before calculation:
    $formula = $worksheet->getCell('B2')->getFormula();
    

Performance Quirks

  • Large Files:
    • Disable unused features (e.g., charts, images) to reduce memory.
    • Use setReadDataOnly(true) to skip metadata:
      $reader = IOFactory::createReader('Xlsx');
      $reader->setReadDataOnly(true);
      $spreadsheet = $reader->load($file);
      

Extension Points

  1. Custom Writers: Extend PhpOffice\PhpSpreadsheet\Writer\WriterInterface for new formats (e.g., CSV with headers).
  2. Cell Value Binders: Override getValueBinder() to transform values on read/write:
    $worksheet->getCell('A1')->setValueBinder(new class implements ValueBinder {
        public function bindToCell(Cell $cell, $value) {
            return strtoupper($value);
        }
    });
    
  3. Event Listeners: Use PhpOffice\PhpSpreadsheet\Event\BeforeSave to modify spreadsheets pre-save:
    $spreadsheet->getEventDispatcher()->addListener(
        'PhpOffice\PhpSpreadsheet\Event\BeforeSave',
        function ($event) {
            $event->getSpreadsheet()->getActiveSheet()->setTitle('Processed');
        }
    );
    

Laravel-Specific Tips

  • Service Provider: Bind PhpSpreadsheet to the container for dependency injection:
    $this->app->singleton(\PhpOffice\PhpSpreadsheet\Spreadsheet::class, function () {
        return new \PhpOffice\PhpSpreadsheet\Spreadsheet();
    });
    
  • Cached Reads: Cache loaded spreadsheets in Laravel's cache:
    $spreadsheet = Cache::remember("spreadsheet_{$fileHash}", now()->addHours(1), function () use ($file) {
        return IOFactory::load($file);
    });
    

Community Resources

  • Stack Overflow: Tag [phpspreadsheet] for troubleshooting.
  • Patreon Articles: Advanced topics (e.g., formulas, conditional formatting).
  • Gitter: Real-time support for edge cases.
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