Reputation: 145
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?
Upvotes: 11
Views: 42754
Reputation: 221
The best way of exporting array to excel is here.
$data = array(
'0' => array('Name'=> 'Parvez', 'Status' =>'complete', 'Priority'=>'Low', 'Salary'=>'001'),
'1' => array('Name'=> 'Alam', 'Status' =>'inprogress', 'Priority'=>'Low', 'Salary'=>'111'),
'2' => array('Name'=> 'Sunnay', 'Status' =>'hold', 'Priority'=>'Low', 'Salary'=>'333'),
'3' => array('Name'=> 'Amir', 'Status' =>'pending', 'Priority'=>'Low', 'Salary'=>'444'),
'4' => array('Name'=> 'Amir1', 'Status' =>'pending', 'Priority'=>'Low', 'Salary'=>'777'),
'5' => array('Name'=> 'Amir2', 'Status' =>'pending', 'Priority'=>'Low', 'Salary'=>'777')
);
$filename = time().".xls";
header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=\"$filename\"");
ExportFile($data);
function ExportFile($records) {
$heading = false;
if(!empty($records))
foreach($records as $row) {
if(!$heading) {
// display field/column names as a first row
echo implode("\t", array_keys($row)) . "\n";
$heading = true;
}
echo implode("\t", array_values($row)) . "\n";
}
exit;
}
Upvotes: 1
Reputation: 41
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.
Upvotes: 4
Reputation: 95101
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);
Upvotes: 31