Add Footer Row in Laravel Excel Export
Hello folks. I am now trying to export transactions for a duration with a header row (for column names), content rows (for each transaction), and a footer (to show the calculation of the total amount from each transaction price). I have done the first two, a header row and the transaction rows. But I am currently stuck with adding a footer row (to show the sum of the price of each transaction) at the end of the transaction rows. I have added the related codes below. Please check them and help me, folks. Thank you all in advance.
I think I may have to use the afterSheet method with RegistersEventListeners but do not know how to actually implement it.
TransactionsExport.php
<?php
namespace App\Exports;
use Carbon\Carbon;
use App\Models\Transaction;
use Maatwebsite\Excel\Events\AfterSheet;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Concerns\WithStyles;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use Maatwebsite\Excel\Concerns\RegistersEventListeners;
use Maatwebsite\Excel\Concerns\WithStrictNullComparison;
class TransactionsExport implements WithHeadings, WithMapping, ShouldAutoSize, FromQuery, WithStyles, WithStrictNullComparison, WithEvents
{
use Exportable, RegistersEventListeners;
public function __construct(int $days)
{
$this->days = $days;
}
public function styles(Worksheet $sheet)
{
return [
// Style the first row as bold text.
1 => ['font' => ['bold' => true]],
];
}
public function query()
{
return Transaction::query()
->with('customer', 'product')
->whereDate('created_at', '>=', Carbon::now()->subDays($this->days))
->orderBy('created_at', 'desc');
}
public function headings(): array
{
return [
'Invoice No.',
'Invoice Type',
'Customer Name',
'Product Name',
'Total Price',
'Paid Amount',
'Balance',
];
}
/**
* @var Transaction $transaction
*/
public function map($transaction): array
{
return [
$transaction->invoice_prefix . $transaction->invoice_no,
$transaction->invoice_type,
$transaction->customer->name,
$transaction->product->name,
$transaction->total_price,
$transaction->payment_amount,
$transaction->balance,
];
}
}
ExportController.php
public function export(Request $request) {
return (new TransactionsExport($request->days))->download('abc.xlsx');
}
Please or to participate in this conversation.