rap2hpoutre/fast-excel
Fast, memory-efficient Excel/CSV/ODS import/export for Laravel using Spout. Export Eloquent models or collections to XLSX/CSV/ODS with custom column mapping, and download from controllers. Import files to collections, configure CSV options, or transform rows into DB inserts.
Installation:
composer require rap2hpoutre/fast-excel
Add to config/app.php (optional for facade):
'FastExcel' => Rap2hpoutre\FastExcel\Facades\FastExcel::class,
First Export:
use Rap2hpoutre\FastExcel\Facades\FastExcel;
// Export a model collection to XLSX
FastExcel::data(User::all())->export('users.xlsx');
First Import:
$data = FastExcel::import('users.xlsx');
FastExcel::data($collection)->export('file.xlsx')fastexcel(User::all())->download('file.xlsx')yield for large datasets (see Implementation Patterns).// Basic export
(new FastExcel(User::all()))->export('users.xlsx');
// With custom column mapping
(new FastExcel(User::all()))->export('users.xlsx', function ($user) {
return [
'Full Name' => $user->name,
'Email' => $user->email,
];
});
// Import CSV and create records
$users = FastExcel::configureCsv(';', '"', 'gbk')
->import('users.csv', function ($line) {
return User::create([
'name' => $line['Name'],
'email' => $line['Email'],
]);
});
// Generator for large datasets
function userGenerator() {
foreach (User::cursor() as $user) {
yield $user;
}
}
// Export without memory spikes
(new FastExcel(userGenerator()))->export('large_export.xlsx');
use Rap2hpoutre\FastExcel\SheetCollection;
$sheets = new SheetCollection([
'Users' => User::all(),
'Projects' => Project::all(),
]);
(new FastExcel($sheets))->export('multi_sheet.xlsx');
Laravel Queues: Offload large exports to background jobs:
ExportUsersJob::dispatch(User::all());
class ExportUsersJob implements ShouldQueue {
public function handle() {
(new FastExcel(User::all()))->export(storage_path('app/users.xlsx'));
}
}
API Endpoints: Secure file downloads:
public function exportUsers() {
return (new FastExcel(User::all()))
->download('users.xlsx')
->setHeader('Content-Disposition', 'attachment; filename="users.xlsx"');
}
Validation: Sanitize imports with Laravel Validation:
$data = FastExcel::import('file.xlsx');
$validated = $data->map(function ($row) {
return Validator::make($row, [
'email' => 'required|email',
'name' => 'required|string',
])->validate();
});
Styling: Apply OpenSpout styles:
use OpenSpout\Common\Entity\Style\Style;
$headerStyle = (new Style())
->setFontBold()
->setBackgroundColor('DDDDDD');
(new FastExcel(User::all()))
->headerStyle($headerStyle)
->export('styled_users.xlsx');
PHP Version:
php.ini or use a Docker container with PHP 8.1+.Memory Limits:
memory_limit may still be hit for >10M rows.memory_limit in php.ini or split exports into smaller files.CSV Encoding:
configureCsv():
FastExcel::configureCsv(';', '"', 'gbk')->import('file.csv');
Sheet Names:
$sheets = new SheetCollection([1 => User::all(), 2 => Project::all()]);
Facade Limitations:
new FastExcel($data)).FastExcel::data($data) or instantiate directly.Import Errors:
null vs. empty string).$data = FastExcel::import('file.xlsx');
\Log::debug('Imported data:', $data->toArray());
Export Corruption:
storage_path() for temporary files:
(new FastExcel(User::all()))->export(storage_path('temp/users.xlsx'));
Performance Bottlenecks:
memory_get_usage():
$start = memory_get_usage();
(new FastExcel(User::all()))->export('file.xlsx');
\Log::info('Memory used:', memory_get_usage() - $start);
Custom Writers:
Rap2hpoutre\FastExcel\FastExcel to add new formats (e.g., JSON Excel).class JsonExcel extends FastExcel {
public function exportJson($file) {
// Custom logic using Spout's WriterInterface
}
}
Event Hooks:
FastExcel to add pre/post-export hooks:
class HookedFastExcel extends FastExcel {
public function export($file) {
\Log::info('Export started');
parent::export($file);
\Log::info('Export finished');
}
}
Batch Processing:
User::chunk(1000, function ($users) {
(new FastExcel($users))->export("users_${chunk}.xlsx");
});
Testing:
FastExcel in unit tests:
$mock = Mockery::mock(FastExcel::class);
$mock->shouldReceive('export')->once();
Spout Under the Hood:
Facade vs. Direct Usage:
new FastExcel($data)).FastExcel::data($data) or instantiate directly in tests.Global Helper:
fastexcel() shares state across calls (e.g., CSV config).fastexcel()->configureCsv(';', '"', 'gbk')->import('file.csv');
fastexcel()->resetCsvConfig()->import('file2.csv'); // Reset for UTF-8
How can I help you explore Laravel packages today?