Reputation: 11
How can I export a table created by PHP into an excel file? Is there any way?
I actually want to do it this way:
Say I am querying the database is a php file and displaying results in a html and PHP table...
This table will be dynamic depending on what the user is searching for. And the users should be able to save the table as a excel file by clicking a EXPORT button...
Is there any option in php to do that?
Upvotes: 1
Views: 1437
Reputation: 619
Take a look a this class. It is able to create multi-sheet excel files from HTML tables.
https://github.com/GSTVAC/HtmlExcel
$xls = new HtmlExcel();
$xls->addSheet("Names", $names);
$xls->headers();
echo $xls->buildFile();
Upvotes: 0
Reputation: 1522
If you do not need formulas or fancy features, it would also be easy to output a CSV file (which Excel can open). If you had an array of arrays like the one enigma demonstrated, you could just use
$string = "";
foreach ($array as $row)
$string .= implode(',', $row) . "\n";
file_put_contents("filename.csv", $string);
Upvotes: 0
Reputation: 1511
If there is an end-user that will view the file use the answer already given using PHPExcel
If your doing it for data-access then use CSV.
https://php.net/manual/en/function.fputcsv.php
$list = array (
array('aaa', 'bbb', 'ccc', 'dddd'),
array('123', '456', '789'),
array('"aaa"', '"bbb"')
);
$fp = fopen('file.csv', 'w');
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
Upvotes: 0
Reputation: 119
store the table in a varaiable
and write into file
ex:
$content = "";//in content you must have table data
$file = fopen("file location", "w");
fwrite($file ,$content);
this should help easy
Upvotes: 0
Reputation: 3491
PHPExcel is probably the best library to go about doing this with. If you download it, there are a ton of examples that will almost certainly show what you want to do.
A quick example would be the following:
$objPHPExcel = new PHPExcel();
$objWorksheet = $objPHPExcel->getActiveSheet();
$objWorksheet->fromArray(
array(
array('', 'Rainfall (mm)', 'Temperature (°F)', 'Humidity (%)'),
array('Jan', 78, 52, 61),
array('Feb', 64, 54, 62),
array('Mar', 62, 57, 63),
array('Apr', 21, 62, 59),
array('May', 11, 75, 60),
array('Jun', 1, 75, 57),
array('Jul', 1, 79, 56),
array('Aug', 1, 79, 59),
array('Sep', 10, 75, 60),
array('Oct', 40, 68, 63),
array('Nov', 69, 62, 64),
array('Dec', 89, 57, 66),
)
);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('sheet.xlsx');
Alternatively, you could export pretty easily as a CSV, which the user could then open in excel without difficulty (not technically an excel document though - there are limitations).
Upvotes: 1