Home > Net >  Laravel export excel from array return empty file
Laravel export excel from array return empty file

Time:12-06

I want to download excel file from array with Laravel

Library:

use Maatwebsite\Excel\Facades\Excel;

This is my code:

$ex = [
    ['one', 'name'],
    ['two', 'family']
];

return Excel::download(new TestExport([$ex]), 'test.xlsx');

My class:

class TestExport
{
    protected $arrays;

    public function __construct(array $arrays)
    {
        $this->arrays = $arrays;
    }

    public function array(): array
    {
        return $this->arrays;
    }
}

But this code download empty xlsx file

CodePudding user response:

I found answer:

class TestExport implements FromCollection, WithHeadings
{
    protected $data;
  
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function __construct($data)
    {
        $this->data = $data;
    }
  
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function collection()
    {
        return collect($this->data);
    }
  
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function headings() :array
    {
        return [
            'ID',
            'Name',
            'Email',
        ];
    }
}

Source: https://www.itsolutionstuff.com/post/laravel-create-csv-file-from-custom-array-using-maatwebsiteexample.html

CodePudding user response:

I appreciate your research to find the answer yourself. Agreeing with your own answer, I also want to emphasize that the Excel library that you are using, accepts Laravel collection, not an array. So, you need to convert your array to a collection using the 'collect' helper function as bellow:

$myCollection = collect($this->ar);

Then export it using Excel facade:

return Excel::download(new TestExport($myCollection), 'test.xlsx');
  • Related