Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export an Array of Arrays to Excel in php

Tags:

arrays

php

excel

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?

like image 245
user1371513 Avatar asked May 03 '12 03:05

user1371513


People also ask

How do I export data from php to Excel?

Export Data from Database:$fileName – Define the name of the excel file to be downloaded. $fields – Define the column named of the excel sheet. $excelData – Add the first row to the excel sheet as a column name. Fetch member's data from the database and add to the row of the excel sheet.

How can I export data from multiple Excel sheets in php?

This is index. php file, in this file first we have make database connection, and fetch data from customer table and display on web page. After this we have make form with input select option for select how many records you want to export in single Excel file and below you can find submit button.

How connect Excel to php?

Establish a ConnectionOpen the connection to Excel by calling the odbc_connect or odbc_pconnect methods. To close connections, use odbc_close or odbc_close_all. $conn = odbc_connect("CData ODBC Excel Source","user","password"); Connections opened with odbc_connect are closed when the script ends.


2 Answers

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);
like image 197
Baba Avatar answered Nov 01 '22 18:11

Baba


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.

like image 38
verni Avatar answered Nov 01 '22 20:11

verni