17

如何使用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');
4

4 回答 4

26

你需要写

$sheet->fromArray([$header], NULL, 'A1');
于 2018-04-28T07:16:52.687 回答
4

另外,您有错误的 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');
于 2020-10-04T15:04:06.277 回答
2

一个更详细的例子

$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

还有更多好的例子 https://phpspreadsheet.readthedocs.io/en/latest/topics/calculation-engine/#examples_1

于 2021-12-03T03:05:51.920 回答
1

您需要包含命名空间

        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
于 2019-05-17T14:58:23.937 回答