Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
laravel
php

How to export models to Excel as multiple sheets in Laravel

Chinweuba Elijah Azubuike

Overview

In this shot, we will learn how to export multiple models from a database to an Excel sheet, and also name the sheet.

We will use the FastExcel package to carry out this task.

Package installation

You can use a composer command to install the package:

composer require rap2hpoutre/fast-excel

Code example

<?php

namespace use App\Models\User;
use App\Models\Project;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Rap2hpoutre\FastExcel\FastExcel;
use 
class exportModels extends Controller
{
  public function index(){
$sheets = new SheetCollection([// creating a sheet collection
    'Users' => User::all(),//Fetch users model with sheet name as user
    'Second sheet' => Project::all()//Fetch project model with sheet name as project 
]);
(new FastExcel($sheets))->export('file.xlsx');// passing the created sheet model and saving the file as `*file.xlsx*
}
}

Explanation

In the example above, we create a sheet collection that helps save both the users and projects models. Then, we pass the models to FastExcel, which fetches the model data to the Excel sheet alongside the export method, which allows us to name the file and save it.

RELATED TAGS

communitycreator
laravel
php

CONTRIBUTOR

Chinweuba Elijah Azubuike
RELATED COURSES

View all Courses

Keep Exploring