Write data from array to sheet using phpspreadsheet library

不羁的心 提交于 2021-02-08 12:32:55

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!