Generate Excel Files in Laravel - The generate or export excel file feature may be needed in a system, especially if the system is an information system or a back office system for example. Now to generate or export excel files in the laravel framework is very easy. We can use the package from laravel-excel.com. In this post, I will explain how to make an excel file generate or export feature in laravel. And in this experiment, I will use the source code of the company profile website that I previously shared on Bisabos.com/Laravel-Company-Profile.
Alright, let's start with the following steps:
Open the project company profile folder
Open a terminal and go to the project directory
Run the command to install the laravel excel package from the maatwebsite in the project we are using.
composer require maatwebsite/excel
- Because in this experiment, we will try to add the export excel feature in the team menu so we need to create a TeamsExport file. To create the Export file, you can use the command below.
php artisan make:export TeamsExport --model=Team
With the command above, it will create us the TeamsExport file in the new export folder.
- In this experiment we use a project that uses the laravel framework version 8, so we need to adjust the code created in step no. 4.
Go to the App\Exports\TeamExports.php file then make the changes as below.
use App\Team;
change to
use App\Models\Team;
- Open the TeamController.php file, then make changes as below.
Add code
use App\Exports\TeamsExport;
use Maatwebsite\Excel\Facades\Excel;
And
public function export()
{
return Excel::download(new TeamsExport, 'team.xlsx');
}
- Then in the route>web.php file add the code as below
use App\Exports\TeamExport;
And
Route::get('teams/export/', [TeamController::class, 'export'])->name('export');
- Then lastly, we need to add an export button in the view. Open the index.blade.php file in resources>views>admin>team>index.blade.php
Then add the code below, just below the "create team" button.
<a href="{{ route('export') }}" class="btn btn-primary">Export Excel</a>
Done. Now we can try to run php artisan serve and go to admin>team menu. There is already an export excel button that can be directly used to generate or export excel.
Thank's for your attention and don't forget to visit Codelapan.com, to get articles about web programming, web design, and others.
Top comments (0)