Convert Figma logo to code with AI

rap2hpoutre logofast-excel

🦉 Fast Excel import/export for Laravel

2,086
246
2,086
84

Top Related Projects

4,220

Read and write spreadsheet files (CSV, XLSX and ODS), in a fast and scalable way

A pure PHP library for reading and writing spreadsheet files

A Python module for creating Excel XLSX files.

Lightweight XLSX Excel Spreadsheet Writer in PHP

🚀 Supercharged Excel exports and imports in Laravel

Quick Overview

Fast-Excel is a PHP library designed for fast and efficient reading and writing of Excel files. It focuses on speed and memory efficiency, making it suitable for handling large Excel files without consuming excessive resources.

Pros

  • High performance for reading and writing large Excel files
  • Low memory usage compared to other Excel libraries
  • Simple and intuitive API for easy integration
  • Supports both XLSX and CSV formats

Cons

  • Limited formatting options compared to more comprehensive Excel libraries
  • Lacks support for complex Excel features like formulas and charts
  • May not be suitable for projects requiring advanced Excel manipulation

Code Examples

Reading an Excel file:

use OpenSpout\Reader\XLSX\Reader;

$reader = new Reader();
$reader->open('file.xlsx');

foreach ($reader->getSheetIterator() as $sheet) {
    foreach ($sheet->getRowIterator() as $row) {
        // Process each row
        var_dump($row);
    }
}

$reader->close();

Writing a simple Excel file:

use OpenSpout\Writer\XLSX\Writer;

$writer = new Writer();
$writer->openToFile('file.xlsx');

$writer->addRow(['Name', 'Age', 'City']);
$writer->addRow(['John Doe', 30, 'New York']);
$writer->addRow(['Jane Smith', 25, 'London']);

$writer->close();

Adding multiple sheets:

use OpenSpout\Writer\XLSX\Writer;

$writer = new Writer();
$writer->openToFile('multi_sheet.xlsx');

$sheet1 = $writer->getCurrentSheet();
$sheet1->setName('Sheet 1');
$writer->addRow(['Data for Sheet 1']);

$writer->addNewSheetAndMakeItCurrent();
$sheet2 = $writer->getCurrentSheet();
$sheet2->setName('Sheet 2');
$writer->addRow(['Data for Sheet 2']);

$writer->close();

Getting Started

  1. Install Fast-Excel using Composer:

    composer require rap2hpoutre/fast-excel
    
  2. Basic usage example:

    use Rap2hpoutre\FastExcel\FastExcel;
    
    // Reading
    $collection = (new FastExcel)->import('file.xlsx');
    
    // Writing
    $data = collect([
        ['name' => 'John Doe', 'email' => 'john@example.com'],
        ['name' => 'Jane Doe', 'email' => 'jane@example.com'],
    ]);
    (new FastExcel($data))->export('file.xlsx');
    

This setup allows you to quickly start using Fast-Excel for basic Excel file operations in your PHP projects.

Competitor Comparisons

4,220

Read and write spreadsheet files (CSV, XLSX and ODS), in a fast and scalable way

Pros of Spout

  • More feature-rich, supporting both reading and writing of spreadsheets
  • Handles large files efficiently with low memory usage
  • Supports multiple spreadsheet formats (XLSX, CSV, ODS)

Cons of Spout

  • Slightly more complex API, requiring more setup code
  • Slower performance for simple, small-scale operations
  • Less actively maintained (last release in 2021)

Code Comparison

Fast-Excel (writing):

$fastExcel = new FastExcel();
$fastExcel->data($data)->export('file.xlsx');

Spout (writing):

$writer = WriterFactory::create(Type::XLSX);
$writer->openToFile($filePath);
$writer->addRows($data);
$writer->close();

Both libraries offer straightforward APIs for writing Excel files, but Fast-Excel provides a more concise syntax for simple operations. Spout requires more explicit setup and closing of the writer object, which can be beneficial for more complex scenarios but may be overkill for basic tasks.

Fast-Excel is focused on speed and simplicity, making it ideal for quick exports of data to Excel format. Spout, on the other hand, offers more flexibility and features, including support for reading spreadsheets and handling various file formats, at the cost of a slightly more verbose API.

A pure PHP library for reading and writing spreadsheet files

Pros of PhpSpreadsheet

  • More comprehensive feature set, supporting a wide range of Excel functionalities
  • Better support for complex formulas and cell formatting
  • Actively maintained with regular updates and improvements

Cons of PhpSpreadsheet

  • Slower performance, especially when dealing with large datasets
  • Higher memory consumption compared to Fast-Excel
  • Steeper learning curve due to its extensive API

Code Comparison

PhpSpreadsheet:

$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'Hello World');
$writer = new Xlsx($spreadsheet);
$writer->save('hello_world.xlsx');

Fast-Excel:

$sheets = new FastExcel();
$sheets->addSheet([[
    'Hello' => 'World'
]]);
$sheets->export('hello_world.xlsx');

Fast-Excel offers a more straightforward API for basic operations, while PhpSpreadsheet provides more granular control over spreadsheet creation and manipulation. PhpSpreadsheet is better suited for complex Excel operations, while Fast-Excel excels in scenarios where performance is crucial, especially when working with large datasets or generating simple spreadsheets.

A Python module for creating Excel XLSX files.

Pros of XlsxWriter

  • More feature-rich, supporting a wide range of Excel functionalities
  • Better documentation and extensive examples
  • Actively maintained with frequent updates

Cons of XlsxWriter

  • Slower performance for large datasets
  • Higher memory usage, especially for complex spreadsheets
  • Steeper learning curve due to more complex API

Code Comparison

XlsxWriter:

import xlsxwriter

workbook = xlsxwriter.Workbook('example.xlsx')
worksheet = workbook.add_worksheet()
worksheet.write('A1', 'Hello')
worksheet.write('B1', 'World')
workbook.close()

FastExcel:

use OpenSpout\Writer\XLSX\Writer;

$writer = new Writer();
$writer->openToFile('example.xlsx');
$writer->addRow(['Hello', 'World']);
$writer->close();

XlsxWriter offers more control and flexibility, allowing for detailed customization of cells and worksheets. FastExcel, on the other hand, provides a simpler API focused on quickly writing data to Excel files. XlsxWriter is Python-based, while FastExcel is primarily used in PHP environments, which may influence the choice depending on the project's tech stack.

Lightweight XLSX Excel Spreadsheet Writer in PHP

Pros of PHP_XLSXWriter

  • Lightweight and has minimal dependencies
  • Supports streaming, allowing for creation of large files with low memory usage
  • Provides more fine-grained control over cell formatting and styles

Cons of PHP_XLSXWriter

  • Less actively maintained compared to Fast-Excel
  • Documentation is not as comprehensive
  • Lacks some advanced features like formula support

Code Comparison

PHP_XLSXWriter:

$writer = new XLSXWriter();
$writer->writeSheetHeader('Sheet1', array('Name' => 'string', 'Age' => 'integer'));
$writer->writeSheetRow('Sheet1', array('John Doe', 30));
$writer->writeToFile('example.xlsx');

Fast-Excel:

$sheets = SheetCollection::make([
    'Sheet1' => [
        ['Name' => 'John Doe', 'Age' => 30]
    ]
]);
FastExcel::data($sheets)->export('example.xlsx');

Both libraries offer straightforward ways to create Excel files, but Fast-Excel provides a more concise API for simple use cases. PHP_XLSXWriter offers more granular control over the writing process, which can be beneficial for complex scenarios or when optimizing for large datasets.

🚀 Supercharged Excel exports and imports in Laravel

Pros of Laravel-Excel

  • More feature-rich, offering advanced functionality like queuing, chunking, and multiple sheet support
  • Seamless integration with Laravel, including Eloquent and Query Builder
  • Extensive documentation and community support

Cons of Laravel-Excel

  • Heavier and potentially slower for simple tasks
  • Steeper learning curve due to more complex API
  • Requires more system resources

Code Comparison

Laravel-Excel:

use Maatwebsite\Excel\Facades\Excel;

Excel::download(new UsersExport, 'users.xlsx');

Fast-Excel:

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

Summary

Laravel-Excel is a comprehensive solution for Excel operations in Laravel, offering advanced features and seamless integration. However, it may be overkill for simple tasks. Fast-Excel, on the other hand, is lightweight and easy to use, making it ideal for basic Excel operations. The choice between the two depends on the complexity of your project requirements and the level of Laravel integration needed.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Version License StyleCI Tests Total Downloads

Fast Excel import/export for Laravel, thanks to Spout. See benchmarks below.

Quick start

Install via composer:

composer require rap2hpoutre/fast-excel

Export a Model to .xlsx file:

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

// Load users
$users = User::all();

// Export all users
(new FastExcel($users))->export('file.xlsx');

Export

Export a Model or a Collection:

$list = collect([
    [ 'id' => 1, 'name' => 'Jane' ],
    [ 'id' => 2, 'name' => 'John' ],
]);

(new FastExcel($list))->export('file.xlsx');

Export xlsx, ods and csv:

$invoices = App\Invoice::orderBy('created_at', 'DESC')->get();
(new FastExcel($invoices))->export('invoices.csv');

Export only some attributes specifying columns names:

(new FastExcel(User::all()))->export('users.csv', function ($user) {
    return [
        'Email' => $user->email,
        'First Name' => $user->firstname,
        'Last Name' => strtoupper($user->lastname),
    ];
});

Download (from a controller method):

return (new FastExcel(User::all()))->download('file.xlsx');

Import

import returns a Collection:

$collection = (new FastExcel)->import('file.xlsx');

Import a csv with specific delimiter, enclosure characters and "gbk" encoding:

$collection = (new FastExcel)->configureCsv(';', '#', 'gbk')->import('file.csv');

Import and insert to database:

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

Facades

You may use FastExcel with the optional Facade. Add the following line to config/app.php under the aliases key.

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

Using the Facade, you will not have access to the constructor. You may set your export data using the data method.

$list = collect([
    [ 'id' => 1, 'name' => 'Jane' ],
    [ 'id' => 2, 'name' => 'John' ],
]);

FastExcel::data($list)->export('file.xlsx');

Global helper

FastExcel provides a convenient global helper to quickly instantiate the FastExcel class anywhere in a Laravel application.

$collection = fastexcel()->import('file.xlsx');
fastexcel($collection)->export('file.xlsx');

Advanced usage

Export multiple sheets

Export multiple sheets by creating a SheetCollection:

$sheets = new SheetCollection([
    User::all(),
    Project::all()
]);
(new FastExcel($sheets))->export('file.xlsx');

Use index to specify sheet name:

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

Import multiple sheets

Import multiple sheets by using importSheets:

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

You can also import a specific sheet by its number:

$users = (new FastExcel)->sheet(3)->import('file.xlsx');

Import multiple sheets with sheets names:

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

Export large collections with chunk

Export rows one by one to avoid memory_limit issues using yield:

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

// Export consumes only a few MB, even with 10M+ rows.
(new FastExcel(usersGenerator()))->export('test.xlsx');

Add header and rows style

Add header and rows style with headerStyle and rowsStyle methods.

use OpenSpout\Common\Entity\Style\Style;

$header_style = (new Style())->setFontBold();

$rows_style = (new Style())
    ->setFontSize(15)
    ->setShouldWrapText()
    ->setBackgroundColor("EDEDED");

return (new FastExcel($list))
    ->headerStyle($header_style)
    ->rowsStyle($rows_style)
    ->download('file.xlsx');

Why?

FastExcel is intended at being Laravel-flavoured Spout: a simple, but elegant wrapper around Spout with the goal of simplifying imports and exports. It could be considered as a faster (and memory friendly) alternative to Laravel Excel, with less features. Use it only for simple tasks.

Benchmarks

Tested on a MacBook Pro 2015 2,7 GHz Intel Core i5 16 Go 1867 MHz DDR3. Testing a XLSX export for 10000 lines, 20 columns with random data, 10 iterations, 2018-04-05. Don't trust benchmarks.

Average memory peak usageExecution time
Laravel Excel123.56 M11.56 s
FastExcel2.09 M2.76 s

Still, remember that Laravel Excel has many more features.