问题
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');
回答1:
You need to write
$sheet->fromArray([$header], NULL, 'A1');
回答2:
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');
回答3:
You need to include the namespace
$spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
$writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
来源:https://stackoverflow.com/questions/48681839/write-data-from-array-to-sheet-using-phpspreadsheet-library