How to create a new column when exporting a table. Laravel maatwebsite / excel

Viewed 351

Please tell me, how create a new column when exporting(to exel) table. There is a table in DB of this kind: enter image description here

I installed package for export maatwebsite / excel. There is also a my file of model:

class ScheduledInspectionModel extends Model
{
    protected $table = 'scheduled_inspection'; // table name
    protected $fillable = ['name_smp', 'name_control', "verification_start", "verification_end", 'verification_duration'];
    public $timestamps = false;
}

Controller:

class OrganizationsExportController extends Controller
{
    public function export()
    {
        return (new OrganizationsExport)->download('organizations_export.xls');
    }
}

And file with export description:

class OrganizationsExport implements FromCollection, ShouldAutoSize, WithHeadings, WithEvents
{
    use Exportable;
    /**
     * @return \Illuminate\Support\Collection
     */
    public function collection()
    {
        return ScheduledInspectionModel::all();
    }

    public function headings(): array
    {
        return [
            'id',
            'Name SMP',
            'Name Control',
            'Verification Start',
            'Verification End',
            'Verification Duration'
        ];
    }

    public function registerEvents(): array
    {
        return [
            AfterSheet::class => function (AfterSheet $event) {
                $event->sheet->getStyle('A1:F1')->applyFromArray([
                    'font' => [
                        'bold' => true
                    ]
                ]);
            }
        ];
    }
}

The exported table looks like this: enter image description here

The export works :) But I want to create in place of the 'id' column (I can exclude it using map ()), 'Number' column and enter the line numbering accordingly. Please tell me how to do this?

1 Answers

I would use the map() function on the export, here you can tweak the source of each column. I assumed column names in your db, due to not knowing the structure. Add one to the count each time it is transformed and you should be golden, which is done with the ++ operator.

private $count = 0;

public function map(ScheduledInspectionModel $inspection): array
{
    return [
        ++$this->count,
        $inspection->name_smp,
        $inspection->name_control,
        $inspection->verification_start->format('Y-m-d') . ' - ' .$inspection->verification_end->format('Y-m-d'),
        $inspection->duration,
    ];
}

To call format on dates, you have to set the dates array on your model.

class ScheduledInspectionModel {
    protected $dates = [
        'verification_start',
        'verification_end',
    ];
}
Related