1

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

2
  • which library are you using? Commented Dec 5, 2021 at 13:43
  • 1
    @aimme I edited my question. I use Maatwebsite\Excel\Facades\Excel; Commented Dec 5, 2021 at 13:45

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

so mark it as correct answer. welcome to stackoverflow :)
2

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');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.