spatie/simple-excel

repository·main·Indexed 23 days ago

https://github.com/spatie/simple-excel

A PHP package for reading and writing simple Excel (.xlsx, .ods) and CSV files. It utilizes generators and Laravel's LazyCollection to maintain low memory consumption when processing large datasets. Features include automatic file type detection, header transformation (snake_case, custom headers), value formatting, and support for multiple sheets in Excel files. The SimpleExcelWriter allows for row styling via OpenSpout, streaming downloads to the browser, and custom CSV delimiters.

Tokens
4.3K
Snippets
8
Records
34
Agent score
80%

What's inside spatie/simple-excel

  1. How SimpleExcelReader handles file types

    main

    The SimpleExcelReader determines whether to treat a file as a CSV or an Excel file based on its file extension:

    • If the file path ends with .csv, it is treated as a CSV file.
    • If the file path ends with .xlsx, it is treated as an Excel file.
  2. Read CSV or Excel files with SimpleExcelReader

    main

    Use SimpleExcelReader::create($path) to initialize a reader. For CSV files, ensure the path ends in .csv. For Excel files, ensure it ends in .xlsx.

    Calling getRows() returns an instance of Illuminate extbackslash Support extbackslash LazyCollection, which allows for memory-efficient processing of large files using generators. You can use standard Laravel collection methods like each(), filter(), take(), or skip() on the result.

    use Spatie\SimpleExcel\SimpleExcelReader;
    
    // Returns a LazyCollection
    $rows = SimpleExcelReader::create($pathToCsv)->getRows();
    
    $rows->each(function(array $rowProperties) {
       // $rowProperties contains column data as associative array
    });
  3. Style Excel rows and columns

    main

    Since styling is only supported for Excel (.xlsx), you can use OpenSpout styles.

    • Row Styling: Pass a Style object as the second argument to addRow($row, $style).
    • Header Styling: Use setHeaderStyle($style) to style the header row.
    • Column/Row Dimensions: Access the underlying writer via the configureWriter callback in create() to set default column widths, row heights, or specific column widths.
    use Spatie\SimpleExcel\SimpleExcelWriter;
    use OpenSpout\Common\Entity\Style\Style;
    use OpenSpout\Common\Entity\Style\Color;
    
    $style = (new Style())->setFontBold()->setFontColor(Color::BLUE);
    
    $writer = SimpleExcelWriter::create('document.xlsx', configureWriter: function ($writer) {
        $options = $writer->getOptions();
        $options->DEFAULT_COLUMN_WIDTH = 25;
        $options->setColumnWidth(40, 1, 3, 8);
    });
    
    $writer->setHeaderStyle($style);
    $writer->addRow(['Header 1', 'Header 2'], $style);
  4. Upgrade from 2.x to 3.0

    main

    When upgrading from version 2.x to 3.0, note the following breaking changes:

    • OpenSpout dependency: Support for openspout/openspout v4 is added, while support for v3 is dropped.
    • Type Hinting: The library now includes type hinting.
    • Removed Methods: useDelimiter() on SimpleExcelWriter and headerRowFormatter on SimpleExcelReader have been removed.
    • Namespace Changes: Several classes have moved due to the OpenSpout update.
  5. Read Excel or CSV files using SimpleExcelReader

    main

    Use SimpleExcelReader::create($pathToFile) to initialize a reader. The package automatically detects the file type based on the extension: .csv for CSV files and .xlsx for Excel files.

    To process rows with low memory usage, call getRows() which returns a generator, and use the each() method to iterate through the rows.

    use Spatie\
    SimpleExcel\
    \SimpleExcelReader;
    
    SimpleExcelReader::create($pathToFile)->getRows()
       ->each(function(array $rowProperties) {
            // process the row
        });
  6. Write CSV or Excel files with SimpleExcelWriter

    main

    Use SimpleExcelWriter::create($path) to write files. For Excel, use a .xlsx extension.

    Important: For Excel files, the file is not finalized on disk until the instance is garbage collected or you manually call $writer->close().

    Key Methods:

    • addRow(array $row): Adds a single row.
    • addRows(array $rows): Adds multiple rows at once.
    • addHeader(array $headers): Manually sets the header row.
    • noHeaderRow(): Prevents the writer from automatically adding a header row.
    • getNumberOfRows(): Returns the count of rows written (including the header).
  7. Stream Excel files to the browser

    main

    You can stream an Excel file directly to a user's browser using streamDownload().

    If you are generating a large file, call flush() periodically within your loop to prevent memory issues and ensure the browser receives data chunks. Finally, call toBrowser() to initiate the download.

  8. Replace StyleBuilder with Style (v3.x)

    main

    In compatibility with OpenSpout v4, StyleBuilder is removed. You should now use the Style class directly to define cell styles.

    // Old way
    use OpenSpout\
    Writer\Common\Creator\Style\StyleBuilder;
    
    $builder = new StyleBuilder();
    $builder
        ->setFontBold()
        ->setFontName('Sans');
    
    // New way
    use OpenSpout\Common\Entity\Style\Style;
    
    $style = new Style();
    $style
        ->setFontBold()
        ->setFontName('Sans');
  9. Create additional sheets in Excel

    main
    By default, SimpleExcelWriter writes to the first sheet. To add more sheets, use addNewSheetAndMakeItCurrent() to create a new sheet and switch the writer's focus to it. You can also use nameCurrentSheet($name) to rename the active sheet.
  10. Transform headers and values in SimpleExcelReader

    main

    Clean up data during the reading process:

    • Snake Case: Use headersToSnakeCase() to convert all header keys to snake_case.
    • Custom Header Formatting: Use formatHeadersUsing(Closure $callback) to transform header names.
    • Trim Headers: Use trimHeaderRow() to strip whitespace from header names.
    • Trim Values: Use trimValues() to strip whitespace from all cell values. You can pass an optional string of characters to trim (e.g., trimValues('*')).
    • Custom Value Formatting: Use formatValuesUsing(Closure $callback) for full control. The closure receives ($value, $key).
    // Convert headers to snake_case and trim whitespace from values
    $rows = SimpleExcelReader::create($pathToCsv)
        ->headersToSnakeCase()
        ->trimValues()
        ->getRows();
    
    // Custom value formatting
    $rows = SimpleExcelReader::create($pathToCsv)
        ->formatValuesUsing(function ($value, $key) {
            return $key === 'email' ? strtolower($value) : $value;
        })
        ->getRows();