Programming
We provide developers and engineers the guides and tutorials they...
Search
We provide developers and engineers the guides and tutorials they...
Content is king. It's not just about how you're going to write, b...
Looking for an engaging connection with thousands of other people...
Exporting Excel files come handy when you're building some inventory kind of an application. In this short tutorial, we'll go through on exporting excel files with Laravel & look on for some crazy hacks and tricks in between.
Exporting Excel files come handy when you're building some inventory kind of an application. In this short tutorial, we'll go through on exporting excel files with Laravel & look on for some crazy hacks and tricks in between.
composer require maatwebsite/excel
Right into your config/app.php, add the service provider.
'providers' => [ Maatwebsite\Excel\ExcelServiceProvider::class, ]
and the facade
'aliases' => [ 'Excel' => Maatwebsite\Excel\Facades\Excel::class, ]
Route::get( '/export', 'DataExporter@index' );
class DataExporter {
public function index() {
\Excel::create( 'file_name', function ( $excel ) {
/** Set the spreadsheet title, creator, and description */
$excel->setTitle( 'your_file_title' );
$excel->setCreator( 'creator_name' )->setCompany( 'company_name' );
$excel->setDescription( 'This is the description of the exported excel file' );
/** Creating a simple sheet */
$excel->sheet( 'sheet_name', function ( $sheet ) {
/** Manipulating Rows */
$sheet->row( '1', array(
'First Row Heading'
) );
$users = User::all();
/**
* Filter through each of users
* @var $key
* @var $value
*/
foreach ( $users as $key => $value ) {
$sheet->SetCellValue( "A" . $key, $value->name );
}
} );
} )->get( 'xlsx' );
}
}There's been major changes in the newer version of this package. So we'll be using the similar User collection approach and will achieve it using the newer version.
We'll move the User collection to a separate file. Let's name is UserExporter.php
class UserExporter implements FromCollection, WithHeadings,ShouldAutoSize {
/**
* @return Collection
*/
public function collection() {
return User::all();
}
/**
* @return array
*/
public function headings(): array {
return [
'First Row Heading',
];
}
}Now back to our DataExporter class, let's simply things up a little in our index() method.
return Excel::download( new UserExporter(), 'users.xlsx' );
Well thats it, simply hit the /export in your browser and you'll get a popup to download your excel file. Generating an excel export was never this simple before. For more information about this awesome package, check out the documentation website.