Search code examples
phpexcellaravellaravel-excel

How to split an excel file into multiple worksheets with laravel-excel


So I managed to create an excel file with data from a students table using Laravel-excel, however, I want it to be split into small worksheets that represent separate groups of 20-25 students.

so far I've only found ways to split it into worksheets based on a condition like a group by sort of thing, but not based on a number of records for each worksheet


Solution

  • You can consider to do:

    Create a StudentExport class:

    namespace App\Exports;
    
    use App\Models\Student;
    use Maatwebsite\Excel\Concerns\Exportable;
    use Maatwebsite\Excel\Concerns\WithMultipleSheets;
    
    class StudentExport implements WithMultipleSheets
    {
        use Exportable;
    
        /**
         * @return array
         */
        public function sheets(): array
        {
            $sheets = [];
            $total = Student::count();
            $maxPage = (int) ceil($total/25);
    
            for ($page = 1; $page <= $maxPage; $page++) {
                $sheets[] = new StudentPerSheet($page);
            }
    
            return $sheets;
        }
    }
    

    Create a StudentPerSheet class

    namespace App\Exports;
    
    use App\Models\Student;
    use Maatwebsite\Excel\Concerns\FromQuery;
    use Maatwebsite\Excel\Concerns\WithTitle;
    
    class StudentPerSheet implements FromQuery, WithTitle
    {
        private $page;
    
        public function __construct(int $page)
        {
            $this->page = $page;
        }
    
        public function query()
        {
            return Student
                ::query()
                ->offset(($this->page - 1) * 25)
                ->limit(25);
        }
    
        /**
         * @return string
         */
        public function title(): string
        {
            return 'Page ' . $this->page;
        }
    }
    

    Then:

    public function downloadStudents() 
    {
        return (new StudentExport())->download('students.xlsx');
    }