Laravel exports excel file using maatwebsite library

Tram Ho

Hello bro! Now I will introduce to everyone the maatwebsite library to handle the export of excel file in any laravel project and start creating test project.

Install project laravel

Go to the forder want to place the project and run the following command to create a prj laravel project name is excel offline. If the ‘Permission’ error then run with sudo privileges is fine.
$ composer create-project --prefer-dist laravel/laravel excel Then create the DB and edit the .env file to connect the DB

Run command to generate key
$ php artisan key:generate
Run migrate to create a user table
$ php artisan migrate

So finished project laravel, next we create the sample data for the user table to test their export again offline.
Step 1: Create a new seeder for the users table named UsersTableSeeder.php
$ php artisan make:seeder UsersTableSeeder
Step 2: We now have a UsersTableSeeder.php file in the database / seeds / directory. In the function we will add the command to run the factory
factory(User::class, 100)->create();
and remember to use the User model. The complete UsersTableSeeder.php will look like this:

Next, register the UsersTableSeeder seed in the DatabaseSeeder.php file, the DatabaseSeeder.php file, complete as follows:

Done, now we run the command: php artisan db:seed into the test db will have 100 sample records in the user table, now we start testing export offline.

Install maatwebsite library

run the following command to install the composer require maatwebsite/excel library Run the following command to pulish config php artisan vendor:publish --provider="MaatwebsiteExcelExcelServiceProvider"

Export

  • Create a route so that when this route is called, it will export to Route::get('export', ' [email protected] ')->name('export');
  • Create Controller php artisan make:controller ExportController
  • Running the command below, I created a file named UsersExport to handle the export of php artisan make:export UsersExport --model=User
  • After running the above command, it will create the UsersExport.php file in App Exports UserExport.php, Modify the file as follows

Explain the file above

  • I use App User to use Eloquent in Laravel,
  • Use Maatwebsite Excel’s class to use the export function
  • Headings () function: create column headings
  • Map function ($ user): map the values ​​to output with the heading
  • Next, we will install in the Controller file so we can use the UsersExport.php file, use App UsersExport to select UserController.php.
  • Next fix the controller

That’s it, access to the path created above we will export a file users.xlsx then, you can change the output file format to users.csv or tsv. Thanks mn for interest ? )!

Share the news now

Source : Viblo