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:
namespace AppExports; use MaatwebsiteExcelConcernsFromCollection; class InvoicesExport implements FromCollection { public function collection() { return Invoice::all(); } }
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:
class InvoicesExport implements FromQuery { use Exportable; public function query() { return Invoice::query(); } }
Or, from View HTML table:
class InvoicesExport implements FromView { public function view(): View { return view('exports.invoices', [ 'invoices' => Invoice::all() ]); } }
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:
[ [ 'name' => 'Povilas', 'surname' => 'Korop', 'email' => 'povilas@laraveldaily.com', 'twitter' => '@povilaskorop' ], [ 'name' => 'Taylor', 'surname' => 'Otwell', 'email' => 'taylor@laravel.com', 'twitter' => '@taylorotwell' ] ]
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:
namespace AppExports; use MaatwebsiteExcelConcernsFromCollection; use MaatwebsiteExcelConcernsExportable; use MaatwebsiteExcelConcernsWithHeadings; class CollectionExport implements FromCollection, WithHeadings { use Exportable; public function collection() { return collect([ [ 'name' => 'Povilas', 'surname' => 'Korop', 'email' => 'povilas@laraveldaily.com', 'twitter' => '@povilaskorop' ], [ 'name' => 'Taylor', 'surname' => 'Otwell', 'email' => 'taylor@laravel.com', 'twitter' => '@taylorotwell' ] ]); } public function headings(): array { return [ 'Name', 'Surname', 'Email', 'Twitter', ]; } }
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:
return Excel::download(new CollectionExport(), 'export.xlsx');
Then you would have this as downloaded result:
Option 2. Pass Array into View
Alternatively, you can build this resources/views/exports/xml.blade.php:
<table>
<thead>
<tr>
@foreach($data[0] as $key => $value)
<th>{{ ucfirst($key) }}</th>
@endforeach
</tr>
</thead>
<tbody>
@foreach($data as $row)
<tr>
@foreach ($row as $value)
<td>{{ $value }}</td>
@endforeach
</tr>
@endforeach
</tbody>
</table>
And then have this in your Export class:
namespace AppExports; use IlluminateContractsViewView; use MaatwebsiteExcelConcernsFromView; class BladeExport implements FromView { public function view(): View { return view('exports.xml', [ 'data' => [ [ 'name' => 'Povilas', 'surname' => 'Korop', 'email' => 'povilas@laraveldaily.com', 'twitter' => '@povilaskorop' ], [ 'name' => 'Taylor', 'surname' => 'Otwell', 'email' => 'taylor@laravel.com', 'twitter' => '@taylorotwell' ] ] ]); } }
Controller stays the same, just different class name:
return Excel::download(new BladeExport(), 'export.xlsx');
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.
class BladeExport implements FromView { private $data; public function __construct($data) { $this->data = $data; } public function view(): View { return view('exports.xml', [ 'data' => $this->data ]); } }
So we’re accepting $data as a parameter now. Then, in our Controller we can have this:
$data = [ [ 'name' => 'Povilas', 'surname' => 'Korop', 'email' => 'povilas@laraveldaily.com', 'twitter' => '@povilaskorop' ], [ 'name' => 'Taylor', 'surname' => 'Otwell', 'email' => 'taylor@laravel.com', 'twitter' => '@taylorotwell' ] ]; return Excel::download(new BladeExport($data), 'export.xlsx');
I hope that’s helpful. Check out other examples in official documentation of the package.
Creating a sheet from an array
To create a new file from an array use ->fromArray($source, $nullValue, $startCell, $strictNullComparison, $headingGeneration)
inside the sheet closure.
Excel::create('Filename', function($excel) {
$excel->sheet('Sheetname', function($sheet) {
$sheet->fromArray(array(
array('data1', 'data2'),
array('data3', 'data4')
));
});
})->export('xls');
Alternatively you can use ->with()
.
$sheet->with(array(
array('data1', 'data2'),
array('data3', 'data4')
));
If you want to pass variables inside the closure, use use($data)
$data = array(
array('data1', 'data2'),
array('data3', 'data4')
);
Excel::create('Filename', function($excel) use($data) {
$excel->sheet('Sheetname', function($sheet) use($data) {
$sheet->fromArray($data);
});
})->export('xls');
Null comparision
By default 0 is shown as an empty cell. If you want to change this behaviour, you can pass true as 4th parameter:
// Will show 0 as 0
$sheet->fromArray($data, null, 'A1', true);
To change the default behaviour, you can use
excel::export.sheets.strictNullComparison
config setting.
Eloquent model
It’s also possible to pass an Eloquent model and export it by using ->fromModel($model)
. The method accepts the same parameters as fromArray
Auto heading generation
By default the export will use the keys of your array (or model attribute names) as first row (header column). To change this behaviour you can edit the default config setting (excel::export.generate_heading_by_indices
) or pass false
as 5th parameter:
// Won't auto generate heading columns
$sheet->fromArray($data, null, 'A1', false, false);
Библиотека: https://laravel-excel.com/
установка:
php -d memory_limit=-1 $(which composer) require maatwebsite/excel
добавить в файл config/app.php для ServiceProvider:
// ...
'providers' => [
// ...
/*
* Package Service Providers...
*/
MaatwebsiteExcelExcelServiceProvider::class,
// ...
],
// ...
добавить в файл config/app.php для Facade:
// ...
'aliases' => [
// ...
'Excel' => MaatwebsiteExcelFacadesExcel::class,
],
// ...
добавить конфиг:
php artisan vendor:publish --provider="MaatwebsiteExcelExcelServiceProvider" --tag=config
после выполнения появится файл config/excel.php
Пример перевода массива в EXCEL файл для скачивания
выполнить команду:
php artisan make:export ArrayExport
появится файл app/Exports/ArrayExport.php, его заполнить:
<?php
namespace AppExports;
use AppInvoice;
use MaatwebsiteExcelConcernsFromArray;
class ArrayExport implements FromArray
{
public function array(): array
{
return [
[1, 2, 3],
[4, 5, 6]
];
}
}
создать контроллер:
php artisan make:controller ExcelController
открыть файл app/Http/Controllers/ExcelController.php и добавить метод:
<?php
namespace AppHttpControllers;
use IlluminateHttpRequest;
use AppExportsArrayExport;
use Excel;
class ExcelController extends Controller
{
public function getArray(Request $request)
{
return Excel::download(new ArrayExport, 'array.xlsx');
}
}
добавить в routes/web.php
// ...
use App/Http/Controllers/ExcelController
// ...
Route::get(
'get_array',
[ExcelController::class, 'getArray']
);
по адресу http://example.com/get_array можно будет скачать данный массив в excel
I want to download excel file from array with Laravel
Library:
use MaatwebsiteExcelFacadesExcel;
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
asked Dec 5, 2021 at 13:40
Rez MohsneiRez Mohsnei
1772 silver badges14 bronze badges
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
answered Dec 5, 2021 at 13:52
Rez MohsneiRez Mohsnei
1772 silver badges14 bronze badges
1
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');
answered Dec 5, 2021 at 14:19
Published: Apr 11, 2021 by C.S. Rhymes
Sometimes you need to get data out of your Laravel app so it can be analysed. There are many ways of doing this, such as exporting rows from the database, or using a package such as Laravel Excel, but this example will utilise Laravel Resource Collections.
In this example we are going to create an export of User information into Excel using Laravel Resource Collection and Spatie’s simple excel package. Laravel Resources are normally used to transform your data for use in an API, but you can also create an array from the resource for use in our export.
The users table has been updated so a user belongs to a company. The companies table has a name for the company in this example.
// App/Models/User.php
public function company()
{
return $this->belongsTo(AppModelsCompany::class, 'company_id', 'id');
}
Creating the User Resource
To create the user resource we can use the artisan command:
php artisan make:resource UserResource
We can then specify the data we want to include for each user. We will add the name, email and the company name.
<?php
namespace AppHttpResources;
use IlluminateHttpResourcesJsonJsonResource;
class UserResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param IlluminateHttpRequest $request
* @return array
*/
public function toArray($request)
{
return [
'name' => $this->name,
'email' => $this->email,
'company' => $this->company->name,
];
}
}
Converting the User Resource to an array
When you return the UserResource it will provide you with a json response with the users within the data key. This is perfect for use with an API.
return UserResource::collection(User::get());
Each user is listed with their name, email and company. The keys are what we defined in the UserResource toArray() method so if we wanted to add additional data, for example such as a company phone number that is added in future, then we can update the UserResource and the results will be updated accordingly.
{
"data": [
{
"name": "Zechariah Olson DDS",
"email": "dreynolds@example.net",
"company": "Boyle Ltd"
}
]
}
We can modify this statement slightly to provide an array of just the user data we need without the data key by using the resolve()
method.
return UserResource::collection(User::get())->resolve();
We can also update the query from User::get()
to User::cursor()
to return a lazy collection and help reduce the amount of memory when we have many users to export. Cursor allows us to only load the current model we are iterating over, rather than loading all models at once.
return UserResource::collection(User::cursor())->resolve();
Exporting to Excel
Now we are ready to make use of the Simple Excel package from Spatie to convert our array into an Excel file.
composer require spatie/simple-excel
The simple excel package provides a writer to help us easily create an excel file using SimpleExcelWriter::create()
but since the file could be very large if our Laravel app has numerous users we can use the SimpleExcelWriter::streamDownload()
method instead to allow us to stream the download directly to the browser.
Once we have our writer instance we can add rows of data to the file using the ->addRows()
method which expects an array. This is where we pass in our UserResource, with the resolve method so it is converted into an array.
Finally we add ->toBrowser()
to return the response to the browser and allow the file to download.
// App/Controllers/UserController.php
public function export()
{
return SimpleExcelWriter::streamDownload('users-export.xlsx')
->addRows(
UserResource::collection(User::cursor())
->resolve()
)
->toBrowser();
}
Other possibilities
Once you have created the resource you can reuse it as it was originally intended as an API response, but you could also use it with another Spatie package called array to xml to convert your array into an XML file instead of a CSV or Excel file.
Photo by Matt Bango from StockSnap
If you have a large number of records stored in a database, it could be useful to share that data as a different format. This article will go through exporting the data from a database into a spreadsheet that can be an .xls/.xlsx file for use with spreadsheet software, or as a .csv so it can be read by a large number of software. I will also go through exporting an array or object to a spreadsheet.
To start off, you’ll need a laravel project. Do note that this article will presume a reasonable knowledge of laravel.
Then you’ll need to install the Excel plugin, which you can get from here: http://www.maatwebsite.nl/laravel-excel/docs .
You’ll also need some data in a database, or in an array or object.
So to start off, I’ll demonstrate how an entire table of values can be exported to a .xlsx or .csv file.
Beginning in the controller, you’ll need to import the Excel plugin by adding
use MaatwebsiteExcelFacadesExcel; to the top of the file.
Then you’ll need a function for this process, and within that we can get down to exporting our table. In the example I’m demonstrating, I will be exporting a table of user data. You should be able to simply just replace the name of the table/variable.
The first step is to collect the data from the table:
$users = User::all();
Next, you’ll need to open the function that builds the spreadsheet, declaring the file name (in this case, users), referencing the Excel plugin, and passing in the $users array:
Excel::create('users', function ($excel) use ($users) {
Within this function, we build the spreadsheet by specifying the name of the sheet, and passing in the $users array:
$excel->sheet('sheet1', function ($sheet) use ($users) {
$sheet->fromArray($users);
});
This process with creating the sheet can be repeated within this function if you intend to create multiple sheets; although you would need to change the name of the sheet for each one you create.
Finally, you just close out the function with your method of exporting, which could be
})->download(‘xlsx’); , or
})->download(‘csv’); , for example. The use of
download would send the file to the device of the user accessing the route. This can be replaced with
->store(‘xlsx’, $storagePath); if you want to store the file on the server in a specific location, just passing in your intended location in place of $storagePath. Another alternative to download and store is
export.
The file type (.xlsx, .csv, etc.) can be replaced with the file extension you want to download/store the file with, such as .xls, .xlsx, .csv or .pdf.
public function csv()
{
$users = User::all();
// Generate and return the spreadsheet
Excel::create('users', function ($excel) use ($users) {
// Build the spreadsheet, passing in the users array
$excel->sheet('sheet1', function ($sheet) use ($users) {
$sheet->fromArray($users);
});
})->download('xlsx');
}
When it comes to exporting an array or object to a spreadsheet file, the process is largely the same, only the variable you’re working with isn’t from the database, but declared as an array. Here is an example of the same code as above, but done by assigning data to an array and exporting that array instead of the user table:
public function csv()
{
$users = User::all();
foreach ($users as $user) {
$userData[] = [
'ID' => $user->id,
'Name' => $user->name,
'Address' => $user->address,
'Postcode' => $user->postcode,
];
}
// Generate and return the spreadsheet
Excel::create('users', function ($excel) use ($userData) {
// Build the spreadsheet, passing in the users array
$excel->sheet('sheet1', function ($sheet) use ($userData) {
$sheet->fromArray($userData);
});
})->download('csv');
}
This example is filling the array with values from the database but you can also manually input the values, or receive values from a form request.
By doing this using an array created in the function as opposed to just outputting all the data from the database, I can specify the headers in the spreadsheet, and only export the specific fields I want to be included in the spreadsheet. But outputting from an array is the way to go when specifying specific data in the function, or when working with data from a form request. Again, as with the previous example, you can change the final line of the function to specify the file type or change the method of outputting the spreadsheet file, be it pushing the download, storing it on the server, etc.
Today, We want to share with you laravel excel export example.In this post we will show you import csv or excel file and export csv or excel file using maatwebsite/excel version 3 composer package, hear for how to export import Excel spreadsheet or csv file to database in php laravel framework. we will give you demo and example for implement.In this post, we will learn about using maatwebsite/excel laravel with an example.
Laravel Import Export Excel to database Example
The simple way to start an export is to make a custom export class. We’ll use members an invoices export as example. how to comfortably import export excel or CSV file to Database file from the database with the maatwebsite/excel composer package in Laravel Application.
Follow Bellow Few Step:
- 1) Install Required Packages
- 2) Configuration app.php file
- 3) Create route
- 4) Create controller
- 5) Create view file
simple way put composer.json this code
and then run this commands “composer update”.
"require": { "php": ">=5.6.4", "laravel/framework": "5.4.*", "laravel/tinker": "~1.0", "maatwebsite/excel": "~2.1.0" },
Step 1 : Install Laravel Application
composer create-project --prefer-dist laravel/laravel member_shop
Step 2: Install Maatwebsite Package
In second methos for install any package it very easy. open terminal and run bellow command then you can install your any required package.
composer require maatwebsite/excel
config/app.php
'providers' => [ .... MaatwebsiteExcelExcelServiceProvider::class, ], 'aliases' => [ .... 'Excel' => MaatwebsiteExcelFacadesExcel::class, ],
and then simple you can make publish configuration file by using following command:
php artisan vendor:publish
and then here create a new config file named “config/excel.php”.
Step 3: Create Dummy Records
php artisan migrate
php artisan tinker factory(AppMember::class, 50)->create();
Step 4: Add Routes
routes/web.php
Route::get('export', '[email protected]')->name('export'); Route::get('membersImpExpList', '[email protected]'); Route::post('import', '[email protected]')->name('import');
Step 5: Create Import Class
php artisan make:import MembersImport --model=Member
app/Imports/MembersImport.php
<?php namespace AppImports; use AppMember; use MaatwebsiteExcelConcernsToModel; class MembersImport implements ToModel { /** * @param array $row * * @return IlluminateDatabaseEloquentModel|null */ public function model(array $row) { return new Member([ 'name' => $row[0], 'email' => $row[1], 'password' => Hash::make('98256'), ]); } }
Step 6: Make Export Class
php artisan make:export MembersExport --model=Member
app/Exports/MembersExport.php
<?php namespace AppExports; use AppMember; use MaatwebsiteExcelConcernsFromCollection; class MembersExport implements FromCollection { /** * @return IlluminateSupportCollection */ public function collection() { return Member::all(); } }
Step 7: Create a Laravel Controller
app/Http/Controllers/MemberController.php
<?php namespace AppHttpControllers; use IlluminateHttpRequest; use AppExportsMembersExport; use AppImportsMembersImport; use MaatwebsiteExcelFacadesExcel; class MemberController extends Controller { /** * @return IlluminateSupportCollection */ public function membersImpExpList() { return view('import'); } /** * @return IlluminateSupportCollection */ public function export() { return Excel::download(new MembersExport, 'members.xlsx'); } /** * @return IlluminateSupportCollection */ public function import() { Excel::import(new MembersImport,request()->file('file')); return back(); } }
Step 8: Create Blade File
resources/views/import.blade.php
<!DOCTYPE html> <html> <head> <title>Laravel PHP Import Export Excel to database Example - www.pakainfo.com</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" /> </head> <body> <div class="container"> <div class="card bg-light mt-3"> <div class="card-header"> Laravel PHP Import Export Excel to database Example - www.pakainfo.com </div> <div class="card-body"> <form action="{{ route('import') }}" method="POST" enctype="multipart/form-data"> @csrf <input type="file" name="file" class="form-control"> <br> <button class="btn btn-success">Import Member Data</button> <a class="btn btn-warning" href="{{ route('export') }}">Export Member Data</a> </form> </div> </div> </div> </body> </html>
I hope you get an idea about Laravel Import Export Excel & CSV File Tutorial with Example.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.