In this tutorial I will help you to export MySQL table data in a excel file using jquery in your PHP web application. A MySQL table data export in a excel file and download the file automatically in your drive.
You need to careful, when you use jQuery in your page then you must be connect the jquery.min.js file and connect the database page for fetch data from MySQL table.
At first you need to create a page and create a table here. Get some field name in the table, which field names you want. Now fetch the data from MySQL table and display all data using while loop in your page.
Create a input button, where you click and download the table excel format. Give the button id name and you must be set a table id or div id. Now call the all table data in a script using div id and pass the all data in a php page. in the php page all table data transfer into excel format and print it or return excel data and download the excel file.
I will help you with an example and source code in this tutorial, follow the example code:
HTML Page:
<div class="row"> <div class="table" id="user_details"> <table class="table" > <thead class="thead-inverse"> <tr> <th>SL No</th> <th>Name</th> <th>Email</th> <th>Phone</th> <th>Description</th> </tr> </thead> <tbody> <?php $i=1; $qryx=mysqli_query($con,"SELECT * from `contactus` ORDER BY `id` DESC"); while($row=mysqli_fetch_array($qryx)) { ?> <tr> <th scope="row"><?php echo $i; ?></th> <td><?php echo $row['1']; ?></td> <td><?php echo $row['3']; ?></td> <td><?php echo $row['2']; ?></td> <td><?php echo $row['4']; ?></td> </tr> <?php $i++; } ?> </tbody> </table> </div> <div> <input type="button" name="export_excel" id="export_excel" value="Export Excel"> </div> </div>
Script:
<script> $(document).ready(function(){ $("#export_excel").click(function(){ var user_all_data=$("#user_details").html(); //alert(excel_data); var excelpage="excelpage.php?data=" + user_all_data; window.location=excelpage; }); }); </script>
excelpage.php
<?php header("Content-Type: application/vnd.ms-excel"); header("Content-disposition: attachment; filename=".rand().".xls"); echo $_GET["data"]; ?>