Laravel Excel Export and Import Complete Guide
Introduction
Laravel Excel is a powerful package that makes working with Excel files in Laravel applications effortless. Built on top of PhpSpreadsheet, it provides an elegant way to export and import data to various file formats including XLSX, CSV, and more.
Whether you need to generate reports, import user data, or create automated data backups, Laravel Excel has you covered.
Installation
Install the package using Composer:
composer require maatwebsite/excel
Publish the configuration file:
php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider"
Add the service provider to config/app.php (for Laravel < 11):
'providers' => [
Maatwebsite\Excel\ExcelServiceProvider::class,
],
'aliases' => [
'Excel' => Maatwebsite\Excel\Facades\Excel::class,
],
Exporting Data
Create an export class for exporting data:
// app/Exports/UsersExport.php
namespace App\Exports;
use App\Models\User;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
class UsersExport implements FromCollection, WithHeadings
{
public function collection()
{
return User::all(['name', 'email', 'created_at']);
}
public function headings(): array
{
return ['Name', 'Email', 'Created At'];
}
}
Using the Export
// In a controller
use App\Exports\UsersExport;
use Maatwebsite\Excel\Facades\Excel;
public function export()
{
return Excel::download(new UsersExport, 'users.xlsx');
}
Export with Formatting
// app/Exports/UsersExport.php
namespace App\Exports;
use App\Models\User;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithStyles;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
class UsersExport implements FromCollection, WithHeadings, WithStyles
{
public function collection()
{
return User::select('name', 'email', 'role', 'created_at')->get();
}
public function headings(): array
{
return ['Name', 'Email', 'Role', 'Created At'];
}
public function styles(Worksheet $sheet)
{
return [
1 => ['font' => ['bold' => true]],
'A' => ['width' => 30],
'B' => ['width' => 40],
];
}
}
Importing Data
Create an import class for importing data:
// app/Imports/UsersImport.php
namespace App\Imports;
use App\Models\User;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
class UsersImport implements ToModel, WithHeadingRow
{
public function model(array $row)
{
return new User([
'name' => $row['name'],
'email' => $row['email'],
'password' => bcrypt('password'),
]);
}
}
Using the Import
// In a controller
use App\Imports\UsersImport;
use Maatwebsite\Excel\Facades\Excel;
public function import(Request $request)
{
Excel::import(new UsersImport, $request->file('file'));
return back()->with('success', 'Users imported successfully!');
}
Batch Import with Validation
// app/Imports/UsersImport.php
namespace App\Imports;
use App\Models\User;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithValidation;
class UsersImport implements ToModel, WithHeadingRow, WithValidation
{
public function model(array $row)
{
return new User([
'name' => $row['name'],
'email' => $row['email'],
]);
}
public function rules(): array
{
return [
'name' => 'required|string|max:255',
'email' => 'required|email|unique:users,email',
];
}
}
Advanced Features
Chunked Import
// For large files, use chunking
use Maatwebsite\Excel\Concerns\WithChunkReading;
class UsersImport implements ToModel, WithChunkReading
{
public function chunkSize(): int
{
return 1000;
}
}
Multiple Sheet Export
// Export multiple sheets
use Maatwebsite\Excel\Concerns\WithMultipleSheets;
class FinancialReport implements WithMultipleSheets
{
public function sheets(): array
{
return [
new SalesSheet(),
new ExpensesSheet(),
new ProfitSheet(),
];
}
}
Queued Exports
// Queue large exports
use Maatwebsite\Excel\Concerns\WithQueue;
class UsersExport implements FromCollection, WithQueue
{
// Exports will be queued for better performance
}
Best Practices
Summary
Laravel Excel provides a powerful and elegant way to handle Excel files in your Laravel applications. From simple exports to complex multi-sheet reports, this package simplifies the process significantly.
For more information, check out our other tutorials on Form Request Validation and Mailables.