Exporting
Introduction
Tables can be exported to different formats such as CSV, Excel, and PDF. Before continuing, make sure you have installed the Laravel Excel package. You can install it via composer:
composer require maatwebsite/excel
Defining Exports
The Table
class has an exports()
method that can be used to define all the export options. Simply create an Export
instance with the static make()
method and return it from the exports()
method.
use InertiaUI\Table\Table;
class Users extends Table
{
public function exports(): array
{
return [
Export::make(),
];
}
}
By default, the export is set to the Excel type and has a label of Excel Export. The make()
method accepts five arguments to customize the export:
use Maatwebsite\Excel\Excel;
Export::make(
label: 'CSV Export',
filename: 'users.csv',
type: Excel::CSV,
authorize: true,
events: []
);
The type must be one of the constants from the Maatwebsite\Excel\Excel
class. Note that some types, like PDF, require additional configuration.
Authorization
Authorization works the same way as with Row Actions. The authorize
option can be a boolean or a Closure.
Export Events
The events
array enables you to hook into the underlying package events.
use Maatwebsite\Excel\Events\BeforeExport;
Export::make(events: [
BeforeExport::class => function (BeforeExport $event) {
$event->writer->getProperties()->setCreator('John Doe');
},
]);
Check out the documentation for more information.
Customizing Exports
You can customize how each column is exported.
Column Mapping
If you want to change the content of a column when exporting, you can pass a Closure to the exportUsing
argument. Alternatively, you can call the exportUsing()
method.
TextColumn::make('reference', exportAs: function (string $reference) {
return "#REF-{$reference}";
});
The closure accepts a second argument, which is the Model instance.
TextColumn::make('name')->exportAs(function (string $name, User $user) {
return $user->is_active ? $name : "Inactive: {$name}";
});
Column Formatting
You may choose a custom format for each column by passing a Closure or string to the exportFormat
argument. Alternatively, you can call the exportFormat()
method.
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
TextColumn::make('amount', exportFormat: NumberFormat::FORMAT_CURRENCY_USD_SIMPLE);
TextColumn::make('amount')->exportFormat(NumberFormat::FORMAT_CURRENCY_USD_SIMPLE);
Column Styling
You can customize the column styling by passing a Closure or array to the exportStyle
argument. Alternatively, you can call the exportStyle()
method.
use PhpOffice\PhpSpreadsheet\Style\Style;
TextColumn::make('name', exportStyle: ['font' => ['bold' => true]]);
TextColumn::make('email')->exportStyle(function (Style $style) {
$style->getFont()->setBold(true);
});
Exclude Columns
To exclude a column from being exported, pass false
to the exportAs
argument, or call the dontExport()
method.
TextColumn::make('Name', exportAs: false);
TextColumn::make('Name')->dontExport();