This
tutorial will go over how to download Mysql data into Excel file. This is Very useful for generating Excel Reports of Php Applications, and database.
<?php
//database credentials
$username = "user_name";
$password = "password";
$host = "host_name";
$dbname = "database_name";
//Connect to database $connector = mysql_connect($host,$username,$password)
or die("Unable to connect");
//echo "Connections are made successfully::";
//Select database
$selected = mysql_select_db($dbname, $connector)
or die("Unable to connect");
//execute the SQL query and return records
$result = mysql_query("SELECT col1, col2, col3 FROM tablename");
$contents="<table border='1'><tr><th>COL1</th><th>COL2</th><th>COL3</th></tr>";
while($row = mysql_fetch_array($result))
{
$contents.="<tr><td>".$row['col1']."</td>";
$contents.="<td>".$row['col2']."</td>";
$contents.="<td>".$row['col3']."</td></tr>";
}
$contents.="</table>";
//header to make force download the file
$file="Report.xls";
header("Content-type: application/vnd.ms-excel");
//.date() functions add current date to file name
header("Content-Disposition: attachment; filename=Report".date('Y-m-d').".xls");
echo $contents;
mysql_close($connector);
?>
Note:- When you run this script Force download of Excel file starts.
0 comments :