Reputation: 329
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');
Upvotes: 23
Views: 46043
Reputation: 502
An example with more details
$database = [
[ 'Tree', 'Height', 'Age', 'Yield', 'Profit' ],
[ 'Apple', 18, 20, 14, 105.00 ],
[ 'Pear', 12, 12, 10, 96.00 ],
[ 'Cherry', 13, 14, 9, 105.00 ],
[ 'Apple', 14, 15, 10, 75.00 ],
[ 'Pear', 9, 8, 8, 76.80 ],
[ 'Apple', 8, 9, 6, 45.00 ],
];
$criteria = [
[ 'Tree', 'Height', 'Age', 'Yield', 'Profit', 'Height' ],
[ '="=Apple"', '>10', NULL, NULL, NULL, '<16' ],
[ '="=Pear"', NULL, NULL, NULL, NULL, NULL ],
];
$worksheet->fromArray( $criteria, NULL, 'A1' )
->fromArray( $database, NULL, 'A4' );
$worksheet->setCellValue('A12', '=DCOUNT(A4:E10,"Height",A1:B3)');
$retVal = $worksheet->getCell('A12')->getCalculatedValue();
// $retVal = 3
There're more good examples https://phpspreadsheet.readthedocs.io/en/latest/topics/calculation-engine/#examples_1
Upvotes: 4
Reputation: 479
Also, you have the wrong Content-Type header...
For BIFF .xls files
application/vnd.ms-excel
For Excel2007 and above .xlsx files
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
So, fully working code should looks like this:
// $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-Disposition: attachment;filename="myfile.xlsx"');
header('Cache-Control: max-age=0');
$writer = new Xlsx($spreadsheet);
$writer->save('php://output');
Upvotes: 6
Reputation: 69
You need to include the namespace
$spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
$writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
Upvotes: 1