Write data from array to sheet using phpspreadsheet library

Gurpreet Kaur picture Gurpreet Kaur · Feb 8, 2018 · Viewed 22.3k times · Source

How can I create excel sheet column headers from array using phpspreadsheet library?

Below is the code I am trying but it's not working:

    // $header is an array containing column headers
    $header = array("Customer Number", "Customer Name", "Address", "City", "State", "Zip");
    $spreadsheet = new Spreadsheet();
    $sheet = $spreadsheet->getActiveSheet();
    $sheet->fromArray($header, NULL, 'A1');     

    // redirect output to client browser
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment;filename="myfile.xlsx"');
    header('Cache-Control: max-age=0');

    $writer = new Xlsx($spreadsheet);
    $writer->save('php://output');

Answer

Denis picture Denis · Apr 28, 2018

You need to write

$sheet->fromArray([$header], NULL, 'A1');