Installation:
composer require cyber-duck/laravel-excel
Cyberduck\LaravelExcel\ExcelServiceProvider in config/app.php.Cyberduck\LaravelExcel\ExcelLegacyServiceProvider if needed.First Export:
use Cyberduck\LaravelExcel\Facades\Excel;
// Export a collection to Excel
$users = User::all();
Excel::export($users, 'users.xlsx');
users.xlsx saved to storage/app/exports/.First Import:
$file = Excel::import('path/to/file.xlsx');
// $file is now a Collection of arrays (raw Excel 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
);
// Export a collection to a file
Excel::export($collection, 'filename.xlsx');
// 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),
];
});
});
Excel::export(
User::all(),
'styled_users.xlsx',
null,
null,
function ($writer) {
$writer->getStyle()->getFont()->setBold(true); // Bold headers
$writer->getStyle()->getFont()->setSize(12);
}
);
$file = Excel::import('path/to/file.xlsx');
foreach ($file as $row) {
User::create($row); // Assuming $row matches User model
}
$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);
});
$file = Excel::import('path/to/file.xlsx');
$file->each(function ($row) {
User::create([
'name' => $row['full_name'],
'email' => $row['user_email'],
]);
});
public function exportUsers(Request $request)
{
return Excel::export(
User::where('active', $request->active)->get(),
'users_' . now()->format('Y-m-d') . '.xlsx'
);
}
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!');
}
// 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);
}
}
Memory Limits:
chunkExport() or queue the job.memory_limit in php.ini or process in chunks.File Paths:
storage/app/exports/ by default. Ensure this directory is writable.CSV Encoding Issues:
é, ü).Excel::export($users, 'users.csv', null, null, null, 'UTF-8');
Legacy Laravel Support:
Check Raw Data:
$rawData = Excel::import('file.xlsx');
dd($rawData->toArray());
Validate Headers:
snake_case for consistency:
// Excel header: "user_name" → Model field: "name"
$file->each(function ($row) {
User::create(['name' => $row['user_name']]);
});
Log Errors:
try {
Excel::import('file.xlsx')->each(...);
} catch (\Exception $e) {
Log::error("Excel import failed: " . $e->getMessage());
}
Custom Writers:
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'));
}
}
Excel::export($users, 'custom.xlsx', null, null, function ($writer) {
$writer = new CustomWriter();
});
Pre-Import Validation:
$file = Excel::import('file.xlsx');
$validator = Validator::make($file->toArray(), [
'*.email' => 'required|email',
]);
if ($validator->fails()) {
throw new \Exception("Validation errors: " . $validator->errors());
}
Batch Processing:
chunk() for database operations during import:
$file = Excel::import('file.xlsx');
$file->chunk(100)->each(function ($chunk) {
User::insert($chunk->toArray());
});
Disable Events for Bulk Imports:
User::withoutEvents(function () {
$file->each(function ($row) {
User::create($row);
});
});
Use insert() Instead of create():
insert() to avoid mass assignment checks:
$file->each(function ($chunk) {
User::insert($chunk->toArray());
});
Optimize Queries:
N+1 queries in exports by eager loading:
Excel::export(User::with('posts')->get(), 'users_with_posts.xlsx');
How can I help you explore Laravel packages today?