How to add dynamic sum total [Footer] to an array column in laravel excel version 3.1?

Viewed 23

I'm using this reference here > https://docs.laravel-excel.com/3.1/exports/collection.html

I use version 3.1 of Maatwebsite to map the data and extract it via excel file.

This is my controller function to export the data with.

public function exportTestData(Request $request)
{
    $timestamp = Carbon::now()->toDateTimeString();
    $filename = "act-data-({$timestamp}).xlsx";

    // getActData >> the function of the sql raw query
    return Excel::download(new TestDataExport($this->getActData($request, true)), $filename);
}

And it produces this output:

testexport

Question: How do I add a dynamic data that totals the summary of Sales, Income, Both vertically.

I want a desired output like this:

desiredoutput

So basically a custom data that totals the summary and add in dynamically after the end of each array. My Total function array assign to cell H2 totals the data horizontally. How to total each data vertically in this kind of integration. Trying to find any reference to stackoverflow, laracasts, and github but I can't find any good resources to start with. Can somebody help me with this situation? Thanks.

Here's the full code of my export function to understand the coding process.

TestDataExport.php

<?php

namespace App\Exports;

use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithCustomStartCell;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithTitle;
use Maatwebsite\Excel\Events\AfterSheet;

class TestDataExport implements FromCollection, ShouldAutoSize, WithCustomStartCell, WithHeadings, WithTitle, WithEvents
{
    use Exportable;

    /**
     * testDatas.
     *
     * @var string
     */
    protected $actData;

    public function __construct($testDatas)
    {
        $this->testDatas = $testDatas;
    }

    public function startCell(): string
    {
        return 'A2';
    }

    public function registerEvents(): array
    {
        return [
            AfterSheet::class => function (AfterSheet $event) {
                /** @var Sheet $sheet */
                $sheet = $event->sheet;

                // map header data to this cells
                $sheet->mergeCells('E1:H1');
                $sheet->setCellValue('E1', "Summaries");

                $styleArray = [
                    'alignment' => [
                        'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
                    ],
                ];

                $cellRange = 'A1:X1'; // All headers center align
                $event->sheet->getDelegate()->getStyle($cellRange)->applyFromArray($styleArray);
            },
        ];
    }

    /**
    * @return \Illuminate\Support\Collection
    */
    public function collection()
    {
        $testDatas = $this->testDatas;

        if (isset($testDatas)) {
            return collect($testDatas)->map(function ($actData, $key) {

                //define totals
                $totals = ! empty($actData['Summaries']) ? $actData['Summaries']['total'] : '0';

                return [
                    'sales' => ! empty($actData['Summaries']) ? $actData['Summaries']['sales'] : '0',
                    'income' => ! empty($actData['Summaries']) ? $actData['Summaries']['income'] : '0',
                    'both' => ! empty($actData['Summaries']) ? $actData['Summaries']['both'] : '0',
                    'total' => ! empty($totals) ? $totals : '0',
                ];
            });
        }

        return collect([]);
    }

    /**
     * Heading of the excel
     *
     * @return array
     */
    public function headings(): array
    {
        return [
            'Sales',
            'Income',
            'Both',
            'Total',
        ];
    }

    /**
     * Title for each sheet
     *
     * @return string
     */
    public function title(): string
    {
        return 'Test Data Export';
    }
}

UPDATE

I'm using this inside my registerEvents function.

//calculate totals
    
                $sheet->setCellValue('V'. ($sheet->getHighestRow()+1), '=SUM(V3:V'.$sheet->getHighestRow().')');
                $sheet->setCellValue('W'. ($sheet->getHighestRow()+1), '=SUM(W3:W'.$sheet->getHighestRow().')');
                $sheet->setCellValue('X'. ($sheet->getHighestRow()+1), '=SUM(X3:X'.$sheet->getHighestRow().')');
                $sheet->setCellValue('Y'. ($sheet->getHighestRow()+1), '=SUM(Y3:Y'.$sheet->getHighestRow().')');

It's giving me the total value of each rows, but I'm also having a problem. Everytime I added a new total to each row. The total will be incremented by 1.

Output here:

enter image description here

Is there anyway to revamp the code without incrementing it by 1? As of now it will jump from one cell to another

0 Answers
Related