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

vandan's avatar
Level 13

export csv using Maatwebsite Excel

hello guys, i try to export a data using array but given output on sheet is blank here is my code

public function exportPi(Request $request, $id)
{

    $proformaInvoice = ProformaInvoice::with('proformaInvoiceItem')->find($id);
    $table = [];

    $table[] = ['Order Number', $proformaInvoice->order_number];
    $table[] = ['Customer Name', $proformaInvoice->cust_name];
    $table[] = [ '#', 'Supplier','Item Code'];

    // Add data rows
    foreach ($proformaInvoice->proformaInvoiceItem as $rec) {
        $table[] = [ $rec->id, $rec->pili_sup_id,$rec->pili_prd_id ];
    }

    $dataCollection = new Collection($table);

    return Excel::download(function ($output) use ($dataCollection) {
        $output->setTitle('Exported Proforma Invoice');
        $output->sheet('Sheet1', function ($sheet) use ($dataCollection) {
            $sheet->fromArray($dataCollection, null, 'A1', false, false);
        });
    }, 'exported_data.csv');
}

so how to do it?

0 likes
3 replies
vandan's avatar
vandan
OP
Best Answer
Level 13

@dhpandya @tray2 thanks for reply i solved my self as reference i post my answer

here is my code

public function collection() {

$table = [];
$proformaInvoice = ProformaInvoice::with(['customer','proformaInvoiceItem.product','proformaInvoiceItem.supplier'])->find($this->id);

$table[] = ['ORDER NUMBER', $proformaInvoice->order_number ?? ''];
$table[] = ['CUSTOMER NAME', $proformaInvoice->customer->cust_name ?? ''];
$table[] = ['',''];

$table[] = [ 
    '#', 
    'PRODUCT',
    'SUPPLIER',
    'ITEM NO'
];

foreach ($proformaInvoice->proformaInvoiceItem as $rec) {            
    $table[] = [ 
        $rec->id, 
        $rec->product->prd_our_item_no . ' - ' . $rec->product->prd_to_description ?? $rec->product->prd_description,
        $rec->supplier->name ?? '',
        $rec->product->prd_our_item_no ?? '',                    
    ];
}
return collect($table);

}

Please or to participate in this conversation.