How to Export any Details from Database in Excel format with Laravel and maatwebsite?

How to  Export any Details from Database  in Excel format with Laravel and maatwebsite?

To export data to an Excel file in Laravel, you can use the Laravel Excel package, which provides a simple way to export data to Excel and CSV formats. Follow these steps to export data to an Excel file:

steps 1 : Install Laravel Excel for Export: 

Install the Laravel Excel package using Composer: open CMD

         composer require maatwebsite/excel

If you have problem writing the above code you can write any of the following.

 

composer require maatwebsite/excel --with-all-dependencies

Step 2  If you want to register it yourself, add the ServiceProvider in config/app.php:

'providers' => [  

  /*     * Package Service Providers...     */    

Maatwebsite\Excel\ExcelServiceProvider::class,

]

 

 add the Facade in config/app.php:

'aliases' => [ 

   ...   

 'Excel' => Maatwebsite\Excel\Facades\Excel::class,

]

Step 3 Publish Configuration:

 Publish the configuration file to customize settings: open CMD and Enter bellow code.

 php artisan vendor:publish --provider="Maatwebsite\Excel\ExcelServiceProvider" --tag=config

This command will create a excel.php file in the config directory.

Step 4  Create Export class : 

php artisan make:export studentExport --model=model_name

generate this file app Export directory.

Step 5 open export file then write logic :


 public function collection()
   {
       return user::select('name','email')->where('is_admin',0)->get();
   }

Note :  Here user is Model name where i want to fetch data and name, email is database column name. 

Step 6 HTML code :
<a class="btn-primary btn" href="{{route('export_student')}}">Export</a>

Note : here create a button when user click this button then excel fill auto generate or download.

Step 7 make route : 

Route::get('export_student',[studentController::class,'export_student'])->name('export_student');

Step 8  open  controller and write code :
import file :
use App\Models\User;
use App\Exports\studentExport;              // this is export file  
use Maatwebsite\Excel\Facades\Excel; 


   public function export_student()
   {
       return Excel::download(new studentExport,'file_name.xlsx');
   }

Note : finish, now go to Export button then click on it then display excel file generate.

Remember to replace User with your actual model class and adjust the export logic according to your application's requirements. This example exports name and Email users' data, but you can customize it to export specific data or format the exported data as needed.

 
 

 


Share this article







Related Posts




0 Comments



Load more Comments

Post a Comment


helllo
Ocec Copyright text of dont't copyright our content