How to export report in excel format using php

15/04/2017   04:09:04 PM

Hello, This tutorial will explain about downloading the mysql data into excel sheet format using PHP and mysql but you can also export the data in .csv file or .xls file and let user to force download it. Using this code we can generate a report from our MySQL data.

1) Create Database Table

  • First create a database then create table inside your database. I have created a sampledb database inside product table created as you can see in the below image.

2) Create index.php page

<form method="post" action="download.php"><input type="submit" value="download" style="width:75px; height:35px;"/></form><br />
<br />
<table border="1" align="center" style="width:60%;"><tr><th>Sr no</th><th>Product Name</th><th>Product Price</th></tr><tr>
<?php
$con=mysqli_connect("localhost","root","","sampledb");
$result = mysqli_query($con,"SELECT * FROM product");
while($row = mysqli_fetch_array($result))
{
echo "<td>".$row['id']."</font></td>";
echo "<td>".$row['name']."</font></td>";
echo "<td>".$row['price']."</font></td></tr>";
}
echo "</table>";
mysqli_close($con);
?>

 

3) Create download.php page

<table border="1" align="center" style="width:50%;"><tr><th>Sr no</th><th>Product Name</th><th>Product Price</th></tr><tr>
<?php
$con=mysqli_connect("localhost","root","","sampledb");
$result = mysqli_query($con,"SELECT * FROM product");
while($row = mysqli_fetch_array($result))
{
echo "<td>".$row['id']."</font></td>";
echo "<td>".$row['name']."</font></td>";
echo "<td>".$row['price']."</font></td></tr>";
$df="Total_Summery-Report";
header("Content-Type: application/x-msdownload");
header("Content-Disposition: attachment; filename='$df'.xls");
header("Pragma: no-cache");
header("Expires: 0");
}
echo "</table>";
mysqli_close($con);
?>

 


Output

                   

Support us by Sharing