filament icon indicating copy to clipboard operation
filament copied to clipboard

feature: Add configure xlsx writer after open

Open ombimo opened this issue 6 months ago • 0 comments

Description

Currently, in my work, I need to add additional content to an XLS export before exported item. Given OpenSpout writer behavior, which only writes rows sequentially, I propose adding a new hook after the writer is opened or before writing the item.

example exporter

<?php

namespace App\Filament\Exports;

use App\Models\Product;
use Filament\Actions\Exports\ExportColumn;
use Filament\Actions\Exports\Exporter;
use Filament\Actions\Exports\Models\Export;
use Illuminate\Support\Number;
use OpenSpout\Common\Entity\Row;
use OpenSpout\Common\Entity\Style\Style;
use OpenSpout\Writer\XLSX\Writer;

class ProductExporter extends Exporter
{
    protected static ?string $model = Product::class;

    public static function getColumns(): array
    {
        return [
            ExportColumn::make('name'),
            ExportColumn::make('slug'),
            ExportColumn::make('sku')
                ->label('SKU'),
            ExportColumn::make('short_description')
                ->label('Short Description'),
            ExportColumn::make('description')
                ->enabledByDefault(false),
            ExportColumn::make('price')
                ->formatStateUsing(fn (mixed $state): string => '$' . Number::format((float) $state, 2)),
            ExportColumn::make('stock'),
            ExportColumn::make('status'),
            ExportColumn::make('category'),
            ExportColumn::make('image')
                ->label('Image URL')
                ->enabledByDefault(false),
            ExportColumn::make('created_at'),
        ];
    }

    public static function getCompletedNotificationBody(Export $export): string
    {
        $body = 'Your product export has completed and ' . Number::format($export->successful_rows) . ' ' . str('row')->plural($export->successful_rows) . ' exported.';

        if ($failedRowsCount = $export->getFailedRowsCount()) {
            $body .= ' ' . Number::format($failedRowsCount) . ' ' . str('row')->plural($failedRowsCount) . ' failed to export.';
        }

        return $body;
    }

    public function configureXlsxWriterAfterOpen(Writer $writer): Writer
    {
        $writer->addRow(Row::fromValues(
            ['This is a custom header added after opening the XLSX writer.'],
            new Style()->setShouldWrapText(false)
        ));
        $writer->addRow(Row::fromValues(
            ['This is a Sub-header.'],
            new Style()->setShouldWrapText(false)
        ));

        return $writer;
    }
}

example output

image

Visual changes

no visual change

Functional changes

  • [x] Code style has been fixed by running the composer cs command.
  • [x] Changes have been tested to not break existing functionality.
  • [ ] Documentation is up-to-date.

ombimo avatar May 09 '26 15:05 ombimo