Thursday, 21 April 2016

Export MySQL Table Data into Excel Sheet Format in PHP ::::::HEMANT VISHWAKARMA

Here is connection.php file, it will contain our script to database.
$hostname = "localhost";
$username = "root";
$password = "";
$database = "test";
$conn = mysql_connect("$hostname","$username","$password") or die(mysql_error());
mysql_select_db("$database", $conn) or die(mysql_error());

ExportToExcel.php is main file which contain function to export excel sheet. You can simply include this file to your file from which you want to export excel sheet. Include this file like this: include ("ExportToExcel.php");


include ("ExportToExcel.php");


And then call this function:


Here is ExportToExcel.php file:

function ExportExcel($table)
{
 
$filename = "uploads/".strtotime("now").'.csv';
 
$sql = mysql_query("SELECT * FROM $table") or die(mysql_error());
 
$num_rows = mysql_num_rows($sql);
if($num_rows >= 1)
{
$row = mysql_fetch_assoc($sql);
$fp = fopen($filename, "w");
$seperator = "";
$comma = "";
 
foreach ($row as $name => $value)
{
$seperator .= $comma . '' .str_replace('', '""', $name);
$comma = ",";
}
 
$seperator .= "\n";
fputs($fp, $seperator);
 
mysql_data_seek($sql, 0);
while($row = mysql_fetch_assoc($sql))
{
$seperator = "";
$comma = "";
 
foreach ($row as $name => $value)
{
$seperator .= $comma . '' .str_replace('', '""', $value);
$comma = ",";
}
 
$seperator .= "\n";
fputs($fp, $seperator);
}
 
fclose($fp);
echo "Your file is ready. You can download it from <a href='$filename'>here!</a>";
}
else
{
echo "There is no record in your Database";
}
 
 
}


<form name="export" method="post">
     <input type="submit" value="Click Me!" name="submit">
</form>
 
<?php
 
if(isset($_POST["submit"]))
{
ExportExcel("csv");
}
 
?>

No comments:

Post a Comment