使用 phpspreadsheet 库将数据从数组写入工作表

2022-08-30 20:58:36

如何使用库从数组创建Excel工作表列标题?phpspreadsheet

以下是我正在尝试但无法正常工作的代码:

    // $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

你需要写

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

答案 2

另外,您有错误的内容类型标头...


对于 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');

推荐