I have written several systems that show data on a page but also provide a CSV download file either through a textarea with formatted data inside to copy and paste or via a download link and creates a file on the fly.
I recently decided that this wasn’t the best way to do it seeing as the people will want to be using Microsoft Excel to view the data. It is possible to write a spreadsheet using PHP and using an example from AppServ I started to do it this way.
The original link is included above but here is my simplified version with smaller more understandable function naming:
Download the example script here: XLS from PHP Example (723 bytes)
<?php
function xls_BOF() {
echo pack("ssssss", 0x809, 0x8, 0x0, 0x10, 0x0, 0x0);
}
function xls_EOF() {
echo pack("ss", 0x0A, 0x00);
}
function xls_write_cell($row, $col, $value='') {
if (is_numeric($value)) {
echo pack("sssss", 0x203, 14, $row, $col, 0x0);
$value = pack("d", $value);
} else {
$l = strlen($value);
echo pack("ssssss", 0x204, 8 + $l, $row, $col, 0x0, $l);
}
echo $value;
}
// Send Headers to set the Filename and force a download of the contents of the script
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
// Put the filename in \"'s if you want it to include spaces
header("Content-Disposition: attachment;filename=" . $filename . ".xls");
header("Content-Transfer-Encoding: binary ");
xlsBOF(); //Start the Spreadsheet
xls_write_cell(0, 1, 'Column 1');
xls_write_cell(0, 2, 'Column 2');
xls_write_cell(0, 3, 'Column 3');
$row = 1;
for ($i=0; $i<2; $i++) {
xls_write_cell($row, 0, 'Row ' . $row . ' Column ' . $i);
xls_write_cell($row, 1, 'Row ' . $row . ' Column ' . $i);
xls_write_cell($row, 2, 'Row ' . $row . ' Column ' . $i);
$row++;
}
xlsEOF(); //End the Spreadsheet
exit(); //Exit the script after download
?>