Export an Array of Arrays to Excel in php

2020-02-05 10:23发布

问题:

I have an Array of arrays at the beginning of each sub array is the header of the column followed by integers that I want to populate the column. It looks something like this:

Array ( [0] => Array ( [0] => How was the Food? [1] => 3 [2] => 4 ) [1] => Array ( [0] => How was the first party of the semester? [1] => 2 [2] => 4 [3] => 0 ) )

Is there a way to break up the array and get it to export to Excel?

回答1:

Excel can open csv file directly ... try

$array = Array (
        0 => Array (
                0 => "How was the Food?",
                1 => 3,
                2 => 4 
        ),
        1 => Array (
                0 => "How was the first party of the semester?",
                1 => 2,
                2 => 4,
                3 => 0 
        ) 
);

header("Content-Disposition: attachment; filename=\"demo.xls\"");
header("Content-Type: application/vnd.ms-excel;");
header("Pragma: no-cache");
header("Expires: 0");
$out = fopen("php://output", 'w');
foreach ($array as $data)
{
    fputcsv($out, $data,"\t");
}
fclose($out);


回答2:

If you really want to export array to excel, have a look at PHPReport. I have written that class to simplify exporting with phpexcel. It supports xls and xlsx.



标签: php arrays excel