如何使用phpspreadsheet
库从数组创建Excel工作表列标题?
以下是我正在尝试的代码,但它无效:
// $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');
答案 0 :(得分:6)
你需要写
$ sheet-> fromArray([$ header],NULL,'A1');
答案 1 :(得分:1)
此外,您使用了错误的Content-Type标头...
对于BIFF .xls文件
application/vnd.ms-excel
对于Excel2007及更高版本的.xlsx文件
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
因此,可以正常工作的代码应如下所示:
// $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');
答案 2 :(得分:0)
您需要包括名称空间
$spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
$writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);