Home > OS >  Class 'PhpOffice\phpspreadsheet\src\PhpSpreadsheet\Spreadsheet' not found in Laravel
Class 'PhpOffice\phpspreadsheet\src\PhpSpreadsheet\Spreadsheet' not found in Laravel

Time:12-07

In my Laravel project I have used the PhpOffice Spreadsheet for downloading data as excel format from a datatable.

For doing that I need to add code in my controller, route and view.

Controller

I have used below namespaces in my controller

<?php

    namespace App\Http\Controllers;

    use PhpOffice\PhpSpreadsheet\Spreadsheet;
    use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
    use PhpOffice\PhpSpreadsheet\Writer\Xls;
    use App\OfferCustomersDataTbl;

    public function export($type) {
        $offer_customer_data = OfferCustomersDataTbl::all();
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $sheet->setCellValue('A1', 'Id');
        $sheet->setCellValue('B1', 'Name');
        $sheet->setCellValue('C1', 'Email');
        $rows = 2;

        foreach($offer_customer_data as $empDetails){
            $sheet->setCellValue('A' . $rows, $empDetails['id']);
            $sheet->setCellValue('B' . $rows, $empDetails['name']);
            $sheet->setCellValue('C' . $rows, $empDetails['email']);
            $rows  ;
        }

        $fileName = "emp.".$type;
        if($type == 'xlsx') {
        $writer = new Xlsx($spreadsheet);
        } else if($type == 'xls') {
        $writer = new Xls($spreadsheet);
        }
        $writer->save("export/".$fileName);
        header("Content-Type: application/vnd.ms-excel");
        return redirect(url('/')."/export/".$fileName);
    }

Route

Route::get('/export/{type}', 'OfferCustomersDataController@export');

View

<a href="{{ url('/') }}/export/xlsx" class="btn btn-info">Export to .xlsx</a>

But while I click to Download as Excel button for downloading it always gives an error

Class 'PhpOffice\phpspreadsheet\src\PhpSpreadsheet\Spreadsheet' not found

But that Spreadsheet class is in that location I have checked several times.

Where is the problem I can't figure out.

Anybody help please? Thanks in advance

CodePudding user response:

In command line: composer require phpoffice/phpspreadsheet

Then in the controller:

use PhpOffice\PhpSpreadsheet\Spreadsheet;

Use 'namespace' \ 'classname', not absolute link

  • Related