<?php
define('DB_SERVER','localhost');
define('DB_USER','root');
define('DB_PASS' ,'');
define('DB_NAME', 'empdata');
$con = mysqli_connect(DB_SERVER,DB_USER,DB_PASS,DB_NAME);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
index.php
<?php
include('config.php');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>How to generate excel from Mysql data in PHP</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<!--Bootstrap -->
<link rel="stylesheet" href="css/bootstrap.css" type="text/css">
</head>
<body>
<div class="container">
<div class="" style="float: right; margin-right: 35px; margin-bottom: 30px; margin-top: 30px;">
<a href="generate-excel.php" class="btn btn-primary btn-xs pull-right">Generate Excel</a>
</div>
<div> </div>
<div class="row col-md-12 ">
<table class="table table-bordered">
<thead>
<tr>
<th>No.</th>
<th>Name</th>
<th>Email id</th>
<th>Phone Number</th>
<th>Department</th>
<th>Joining Date</th>
</tr>
</thead>
<?php
$query=mysqli_query($con,"select * from tblemploye");
$cnt=1;
while ($row=mysqli_fetch_array($query))
{
?>
<tr>
<td><?php echo $cnt; ?></td>
<td><?php echo $row['fullName']?></td>
<td><?php echo $row['emailId']?></td>
<td><?php echo $row['phoneNumber']?></td>
<td><?php echo $row['department']?></td>
<td><?php echo $row['joiningDate']?></td>
</tr>
<?php
$cnt++;
} ?>
</table>
</div>
</div>
<!-- Loading Scripts -->
<script src="js/jquery.min.js"></script>
<script src="js/bootstrap-select.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</body>
</html>
generate-excel.php
<?php
// Database Connection file
include('config.php');
?>
<table border="1">
<thead>
<tr>
<th>No.</th>
<th>Name</th>
<th>Email id</th>
<th>Phone Number</th>
<th>Department</th>
<th>Joining Date</th>
</tr>
</thead>
<?php
// File name
$filename="EmpData";
// Fetching data from data base
$query=mysqli_query($con,"select * from tblemploye");
$cnt=1;
while ($row=mysqli_fetch_array($query))
{
?>
<tr>
<td><?php echo $cnt; ?></td>
<td><?php echo $row['fullName'];?></td>
<td><?php echo $row['emailId'];?></td>
<td><?php echo $row['phoneNumber'];?></td>
<td><?php echo $row['department'];?></td>
<td><?php echo $row['joiningDate'];?></td>
</tr>
<?php
$cnt++;
// Genrating Execel filess
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=".$filename."-Report.xls");
header("Pragma: no-cache");
header("Expires: 0");
} ?>
</table>
Download