Thursday, February 3, 2011

Export to Excel Using PHP

Hi
Use the Code :
# file name for download Using Headers
$filename = "urfile_data_" . date('Ymd') . ".xls";
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: application/vnd.ms-excel");

$flag = false;
$result = mysql_query($sql) or die('Query failed!');
while(false !== ($row = mysql_fetch_assoc($result))) {
if(!$flag) {
# display field/column names as first row
echo implode("\t", array_keys($row)) . "\n";
$flag = true;
}
array_walk($row, 'cleanData');
echo implode("\t", array_values($row)) . "\n";
}


function cleanData(&$str) {
$str = preg_replace("/\t/", "\\t", $str);
$str = preg_replace("/\r?\n/", "\\n", $str);
if(strstr($str, '"'))
$str = '"' . str_replace('"', '""', $str) . '"';
}

No comments:

Post a Comment