Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

anonymouse703's avatar

How to add custom data at the last row data? - Laravel Excel

I'm using Maat Laravel-Excel. I want to add custom data at the row

Example total Cashin and etc.

I tred this two ways but not working

Code 1

public function afterSheet(AfterSheet $event)
    {
        $sheet = $event->sheet;

        // Calculate the total withdrawal Php and USD
        $totalWithdrawalPhp = DB::table('revenue_snapshots')->sum('total_withdrawn_php');
        $totalWithdrawalUsd = DB::table('revenue_snapshots')->sum('total_withdrawn_usd');

        // Calculate the total net Php and USD
        $totalNetPhp = DB::table('revenue_snapshots')->sum('cashins') - $totalWithdrawalPhp;
        $totalNetUsd = DB::table('revenue_snapshots')->sum('cashins') - $totalWithdrawalUsd;

        // Add the total withdrawal Php and USD to the end of the Excel last record
        $sheet->cell('F' . $sheet->getHighestRow())->setValue($totalWithdrawalPhp);
        $sheet->cell('G' . $sheet->getHighestRow())->setValue($totalWithdrawalUsd);

        // Add the total net Php and USD to the end of the Excel last record
        $sheet->cell('H' . $sheet->getHighestRow())->setValue($totalNetPhp);
        $sheet->cell('I' . $sheet->getHighestRow())->setValue($totalNetUsd);

    }

Code 2

    public function registerEvents(): array
    {
        return [
            AfterSheet::class => function (AfterSheet $event) {
                $lastRow = $event->sheet->getDelegate()->getHighestRow();

                // Calculate the totals
                $totalCashins = DB::table('revenue_snapshots')->sum('cashins');
                $totalWithdrawalPHP = DB::table('revenue_snapshots')->sum('total_withdrawn_php');
                $totalWithdrawalUSD = DB::table('revenue_snapshots')->sum('total_withdrawn_usd');
                $totalNetPHP = 0 - $totalWithdrawalPHP;
                $totalNetUSD = $totalCashins - $totalWithdrawalUSD;

                // Add custom data to the last row
                $event->sheet->appendRow([
                    '',
                    'Total Cashins',
                    'Total Withdrawal PHP',
                    'Total Withdrawal USD',
                    'Total Net PHP',
                    'Total Net USD',
                ]);

                $event->sheet->appendRow([
                    '',
                    $totalCashins,
                    $totalWithdrawalPHP,
                    $totalWithdrawalUSD,
                    $totalNetPHP,
                    $totalNetUSD,
                ]);

                $event->sheet->getStyle('B' . ($lastRow + 1) . ':F' . ($lastRow + 2))->applyFromArray([
                    'font' => ['bold' => true],
                ]);
            },
        ];
    }

this is my current code

<?php

namespace App\Exports;

use App\Models\RevenueSnapshot;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Excel;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithStyles;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use Maatwebsite\Excel\Events\AfterSheet;
use Illuminate\Support\Facades\DB;

class DailyBasicFinancialReportExport implements FromQuery, WithHeadings, ShouldAutoSize, WithStyles
{
    use Exportable;

    private string $writerType = Excel::XLSX;

    protected $startDate;
    protected $endDate;

    public function __construct( $startDate, $endDate)
    {
        $this->startDate = $startDate;
        $this->endDate = $endDate;
    }

    public function query()
    {

        $query = RevenueSnapshot::select(
            'cashins',
            'total_withdrawn_php',
            'total_withdrawn_usd',
            'total_withdrawal_tax_php',
            'total_withdrawal_tax_usd',
            DB::raw("DATE_FORMAT(created_at, '%Y-%m-%d %H:%i:%s %Z') as formatted_created_at")
        );

        if ($this->startDate && $this->endDate) {
            $query->whereBetween('created_at', [$this->startDate, $this->endDate]);
        }

        return $query;


    }

    public function headings(): array
    {
        return [
            'Cashins',
            'Total Withdrawn PHP',
            'Total Withdrawn USD',
            'Total Withdrawal Tax PHP',
            'Total Withdrawal Tax USD',
            'Date'
        ];
    }

    public function styles(Worksheet $sheet)
    {
        return [
            1 => ['font' => ['bold' => true]],
        ];
    }


    public function afterSheet(AfterSheet $event)
    {
        $sheet = $event->sheet;

        // Calculate the total withdrawal Php and USD
        $totalWithdrawalPhp = DB::table('revenue_snapshots')->sum('total_withdrawn_php');
        $totalWithdrawalUsd = DB::table('revenue_snapshots')->sum('total_withdrawn_usd');

        // Calculate the total net Php and USD
        $totalNetPhp = DB::table('revenue_snapshots')->sum('cashins') - $totalWithdrawalPhp;
        $totalNetUsd = DB::table('revenue_snapshots')->sum('cashins') - $totalWithdrawalUsd;

        // Add the total withdrawal Php and USD to the end of the Excel last record
        $sheet->cell('F' . $sheet->getHighestRow())->setValue($totalWithdrawalPhp);
        $sheet->cell('G' . $sheet->getHighestRow())->setValue($totalWithdrawalUsd);

        // Add the total net Php and USD to the end of the Excel last record
        $sheet->cell('H' . $sheet->getHighestRow())->setValue($totalNetPhp);
        $sheet->cell('I' . $sheet->getHighestRow())->setValue($totalNetUsd);

    }


}
0 likes
2 replies
tangtang's avatar

@anonymouse703

did you get error when downloaded? or you dont get the last row in your downloaded excel file ?

code 2 seems fine.

anonymouse703's avatar

@tangtang I changed aftersheet into prepareRows and it's working now.. Thanks sir

this is the corrected code

public function prepareRows($collection)
    {
        // Calculate the total withdrawal Php and USD
        $totalCashinPhp = 0;
        $totalCashinUsd = DB::table('revenue_snapshots')->sum('cashins');
        $totalWithdrawalPhp = DB::table('revenue_snapshots')->sum('total_withdrawn_php');
        $totalWithdrawalUsd = DB::table('revenue_snapshots')->sum('total_withdrawn_usd');

        // Calculate the total net Php and USD
        $totalNetPhp = $totalCashinPhp - $totalWithdrawalPhp;
        $totalNetUsd = $totalCashinUsd - $totalWithdrawalUsd;

        // Create summary rows with labels
        $summaryRows = [
            [
                'Label' => 'Total Cashin Php',
                'Value' => $totalCashinPhp,
            ],
            [
                'Label' => 'Total Cashin USD',
                'Value' => $totalCashinUsd,
            ],
            [
                'Label' => 'Total Withdrawal PHP',
                'Value' => $totalWithdrawalPhp,
            ],
            [
                'Label' => 'Total Withdrawal USD',
                'Value' => $totalWithdrawalUsd,
            ],
            [
                'Label' => 'Total Net PHP',
                'Value' => $totalNetPhp,
            ],
            [
                'Label' => 'Total Net USD',
                'Value' => $totalNetUsd,
            ],
        ];

        // Add the summary rows to the collection
        $collection = $collection->concat($summaryRows);

        return $collection;
    }

Please or to participate in this conversation.