Laravel Excel Maatwebsite - SUM function not working

Viewed 1335

I am using Maatwebsite 3.1 with Laravel 5.8.
I generate a spreadsheet with a prices columns, which I would like to sum. In order to do so I have the following code:

<?php

namespace App\Exports;

use Maatwebsite\Excel\Concerns\FromCollection;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use Maatwebsite\Excel\Concerns\WithStyles;

use \Illuminate\Support\Collection;

class MenuExport implements FromCollection, WithStyles
{
    private $data;

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

    public function styles(Worksheet $sheet)
    {
        $numOfRows = count($this->data);
        $totalRow = $numOfRows + 1;

        // Add cell with SUM formula to last row
        $sheet->setCellValue("B{$totalRow}", "=SUM(B1:B{$numOfRows})");
    }

    public function collection()
    {
        // Add new row with Total cell
        $extendedArr = [
            $this->data,
            ['Total:']
        ];
        
        return new Collection($extendedArr);
    }
}

The generated excel actually has the SUM function, but it show 0. For example, I call the exporter with the following data:

$data = [
    ['Coffee', 1.8],
    ['Cake', 3.6],
    ['Toast', 2.5]
];
        
return Excel::download(new MenuExport($data), "menu.xlsx");

This is the result:
enter image description here

If I cut the function cell content and then paste it - I get the desired result:
enter image description here

Any idea what's wrong?

1 Answers

Actually it was easier than I thought.
All I had to do was to add WithPreCalculateFormulas:

:
use Maatwebsite\Excel\Concerns\WithPreCalculateFormulas;

class MenuExport implements FromCollection, WithStyles, WithPreCalculateFormulas
{

From documentation:

Maatwebsite\Excel\Concerns\WithPreCalculateFormulas
Forces PhpSpreadsheet to recalculate all formulae in a workbook when saving, so that the pre-calculated values are immediately available to MS Excel or other office spreadsheet viewer when opening the file.

Related