Laravel-Excel 3.0: Export Custom Array into Excel

Recently popular package Laravel-Excel released a new version 3.0, which was a pretty radical change from previous versions. I needed to do a simple Excel export and noticed that their documentation covers only export from Laravel Collections but not from some custom structure. So I will show you a “workaround”.

First, this is how documentation describes the basic workflow:

You need to create a separate class for export (similar how Laravel Notifications work) and you can define a collection to export.

There are also other ways to export the data:

From Eloquent query:

Or, from View HTML table:

But still, the problem is that all examples are based on Eloquent. What if I need Excel from some custom structure like array?

Imagine that I have this array:

How do I export that into Excel, so that keys would be columns, and values would be rows?

There are two ways.

Option 1. Turn your Array into a Collection and add Headings

This is how the Export class would look:

You need to implement collection() method by using Laravel’s collect() method and passing array to it. Also, you need to implement headings() to add a header row.

Finally, in Controller you will have this row at the end of the method:

Then you would have this as downloaded result:

laravel excel 3.0 export


Option 2. Pass Array into View

Alternatively, you can build this resources/views/exports/xml.blade.php:

And then have this in your Export class:

Controller stays the same, just different class name:


Wait, but how to pass data into Export class?

Both of our examples have one flaw – the data is formed in the class itself. Actually, it shouldn’t even know about the data, it should accept it as a parameter. But how do we do that, if view() or collection() methods have no parameters?

We will pass it through __construct() method into a private variable. You could call it a dependency injection, although there are much better examples of dependency injection, look it up on Google.

So we’re accepting $data as a parameter now. Then, in our Controller we can have this:

I hope that’s helpful. Check out other examples in official documentation of the package.

Want to generate Laravel adminpanel online?
You don't need any packages to do that!

3 thoughts on “Laravel-Excel 3.0: Export Custom Array into Excel

  1. Very smart notices and hints as we had expected with your Laravel’s articles. However, there is any mention for very large models. i.e suppose a model with more than 2 million records!

  2. Hi, how are you? If you want to add color to the xls cells using xml.blade.php?

    this does not work: NAME or NAME

    any ideas?

Leave a Reply

Your email address will not be published. Required fields are marked *