Array to Excel file

Topics: Developer Forum
May 13, 2009 at 5:46 AM

Hello,

What would be the easiest way to write an array to an xlsx?

Here is my array:

Array ( [0] => Array ( [business] => Lucky Strikes Bowling [street] => [value] => [city] => [state] => [phone] => ) [1] => Array ( [business] => Strikes Bowling Lounge [street] => [value] => [city] => [state] => [phone] => ) [2] => Array ( [business] => AMF Boulevard Lanes [street] => [value] => [city] => [state] => [phone] => ) [3] => Array ( [business] => North Bowl [street] => [value] => [city] => [state] => [phone] => ) [4] => Array ( [business] => Brunswick Erie Lanes [street] => 1300 E Erie Ave [value] => [city] => Philadelphia [state] => PA [phone] => (215) 535-3500 ) [5] => Array ( [business] => Thunderbird Lanes [street] => [value] => [city] => [state] => [phone] => ) [6] => Array ( [business] => Center Bowling Lanes [street] => 7550 City Line Ave [value] => [city] => Philadelphia [state] => PA [phone] => (215) 878-5050 ) [7] => Array ( [business] => Seventy Third Street Lanes [street] => 7235 Elmwood Ave [value] => [city] => Philadelphia [state] => PA [phone] => (215) 365-1626 ) [8] => Array ( [business] => Hi Spot Lanes [street] => [value] => [city] => [state] => [phone] => ) [9] => Array ( [business] => Thunderbird Lanes [street] => 5830 Castor Ave [value] => [city] => Philadelphia [state] => PA [phone] => (215) 743-2521 ) )

Thanks,

Bob Brodie

Developer
May 13, 2009 at 1:15 PM

Try something like this:

$excel = new PHPExcel();
$sheet = $excel->getActiveSheet();

foreach ($contacts as $row => $contact) {
    $col = 0;
    foreach ($contact as $field => $value) {
        $sheet->getCellByColumnAndRow($col, $row + 1)->setValueExplicit($value, PHPExcel_Cell_DataType::TYPE_STRING);
        $col++;
    }
}

$writer = PHPExcel_IOFactory::createWriter($excel, 'Excel2007');
$writer->save('contacts.xlsx');