Creative, Informative and Entertaining Stuff for everyone

Monday February 6th 2012

Categories

Archives

Calender

February 2012
S M T W T F S
« Dec    
 1234
567891011
12131415161718
19202122232425
26272829  

export data to excel file (.xls format)

Bookmark and Share

By using the below code you can export your data from the database to excel file.
When you run the below code, the excel file get generated and get downloaded to the client machine.

$file_name = "Name_of_excel_file";
header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=\"$file_name.xls\"");
echo "\t Put_your_headline_for_the_excelfile ";
echo "\n\n";
// Here put the column title
$heading = "Column_1_title \t Column_2_title \t Column_3_title\t Column_4_title \t Column_5_title \t\n\n";
echo $heading;
$data = '';

$conn = mysql_connect("localhost", "mysql_user", "mysql_password");
if (!$conn)
{
echo "Unable to connect to DB: " . mysql_error();
exit;
}

if (!mysql_select_db("mydbname"))
{
echo "Unable to select mydbname: " . mysql_error();
exit;
}

$sql = "SELECT column_1, column_2, column_3, column_4, column_5
FROM sometable
WHERE somecondition = 1";

$result = mysql_query($sql);

if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}

if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}

// Note: If you're expecting just one row, no need to use a while loop
while ($row = mysql_fetch_assoc($result))
{

echo $data = $row["column_1"]."\t".$row["column_2"]."\t".$row["column_3"]."\t".$row["column_4"]."\t".$row["column_5"]."\t\n";
}
mysql_free_result($result);
?>

Leave a Reply