Laravel Excel is an open-source Laravel library based on PhpSpreadsheet. It provides an easy way to import and export Excel files, supporting multiple formats including XLSX and CSV. Whether you are exporting data from a database or importing data from an Excel file to the database, Laravel Excel makes it easy to handle.
Before you start, you need to install Laravel Excel in your Laravel project. You can install it using the Composer command:
composer require maatwebsite/excel
Once installed, you should register the service provider in your config/app.php. Although Laravel 5.5 and later versions support automatic package discovery, it's a good practice to explicitly register it.
Maatwebsite\Excel\ExcelServiceProvider::class,
'Excel' => Maatwebsite\Excel\Facades\Excel::class,
Exporting data with Laravel Excel is relatively simple. Below is a basic example showing how to export data to an Excel file:
use Maatwebsite\Excel\Facades\Excel;
use App\Exports\UsersExport;
Excel::download(new UsersExport, 'users.xlsx');
To export data, you need to create an Export class, usually located in the `App\Exports` directory. You can generate this class using the following command:
php artisan make:export UsersExport --model=User
Then, in the `UsersExport` class, you can define the data to be exported:
namespace App\Exports;
use App\Models\User;
use Maatwebsite\Excel\Concerns\FromCollection;
class UsersExport implements FromCollection
{
public function collection()
{
return User::all();
}
}
In addition to exporting, Laravel Excel also provides the functionality to import Excel files. To import data, you need to create an Import class:
php artisan make:import UsersImport --model=User
In the `UsersImport` class, implement the data processing logic:
namespace App\Imports;
use App\Models\User;
use Maatwebsite\Excel\Concerns\ToModel;
class UsersImport implements ToModel
{
public function model(array $row)
{
return new User([
'name' => $row[0],
'email' => $row[1],
]);
}
}
Finally, use the following code to import the Excel file:
Excel::import(new UsersImport, 'users.xlsx');
Laravel Excel provides great convenience for handling Excel files. From importing to exporting, you can perform complex operations with simple code. I hope this practical guide helps you quickly get started with handling Excel files in Laravel.
Whether you're working on a small project or a large application, mastering Laravel Excel will provide you with a powerful tool to enhance your development efficiency. Start experimenting now and enjoy the seamless integration with Excel!