Using this plugin: maatwebsite/excel
composer require maatwebsite/excel
You can use this anywhere in your app.
<?php
$array = [
[ 'id' => 1, 'name' => 'john doe', 'email' => 'john.doe@example.com' ],
[ 'id' => 2, 'name' => 'foe bar', 'email' => 'foe.bar@example.com' ],
];
$columns = ['ID', 'Name', 'Email'];
$export = new class($array, $columns) implements
\Maatwebsite\Excel\Concerns\FromArray,
\Maatwebsite\Excel\Concerns\WithHeadings,
\Maatwebsite\Excel\Concerns\ShouldAutoSize
{
use \Maatwebsite\Excel\Concerns\Exportable;
private $array;
private $columns;
public function __construct($array, $columns) {
$this->array = $array;
$this->columns = $columns;
}
public function array(): array {
return $this->array;
}
public function headings(): array {
return $this->columns;
}
};
return $export->download(
'export.xlsx',
\Maatwebsite\Excel\Excel::XLSX
);
// or you can store it on a disk
return $export->store(
'user/export.xlsx',
'public',
\Maatwebsite\Excel\Excel::XLSX
);
Inspired by the official collection macro: /src/Mixins/DownloadCollection.php
$array = [
[ 'id' => 1, 'name' => 'john doe', 'email' => 'john.doe@example.com' ],
[ 'id' => 2, 'name' => 'foe bar', 'email' => 'foe.bar@example.com' ],
];
collect($array)->downloadExcel('export.xlsx', \Maatwebsite\Excel\Excel::XLSX, true);
The collection macro is way easier to use but it does not support auto column sizing.