I’ll show you how to export grid data to an excel file in this post. Export/Import is a relatively popular functionality for web development; nevertheless, there are times when we need to export entire grid data into an excel file.
in which case we should use the approach described below. In PHP, we simply need to set header information to force the browser to launch the download window.
If you are more comfortable in watching a video that explains about Exporting Data to Excel with PHP and MySQL, then you should watch this video tutorial.
You can also check other tutorial of Export Data with PHP,
Because Excel is the finest format for storing data in a file, exporting data in Excel format is a very important tool that allows users to save data for offline use. You’ll learn how to use PHP and MySQL to export data to Excel.
Prerequisites:
Before we get started, ensure that you have the following set up:
So the file structure for this example is the following:
Let’s create a tasks table that ll all tasks records which will export later on in excel format.
CREATE TABLE `tasks` ( `id` int(11) NOT NULL, `Name` varchar(255) NOT NULL, `Status` varchar(255) NOT NULL, `Priority` varchar(255) NOT NULL, `Date` date NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Indexes for table `tasks` -- ALTER TABLE `tasks` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT for table `tasks` -- ALTER TABLE `tasks` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5; COMMIT;
Now, I’ll insert some sample data into the tasks table.
INSERT INTO `tasks` (`id`, `Name`, `Status`, `Priority`, `Date`) VALUES (1, 'Task1', 'Completed', 'Low', '2021-09-01'), (2, 'Task2', 'InProgress', 'High', '2021-03-17'), (3, 'Mysql', 'Hold', 'Low', '2021-09-22'), (4, 'API', 'Pending', 'Low', '2021-09-06');
We’ll create a connection.php
file and add the below code. in this file, We’ll pass the database hostname, database username, database password, and database name.
<?php Class dbObj{ /* Database connection start */ var $dbhost = "localhost"; var $username = "root"; var $password = ""; var $dbname = "test"; var $conn; function getConnstring() { $con = mysqli_connect($this->dbhost, $this->username, $this->password, $this->dbname) or die("Connection failed: " . mysqli_connect_error()); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } else { $this->conn = $con; } return $this->conn; } } ?>
We’ll receive entries from a MySQL database table tasks and put them in an array so we can show them and export them to an excel file. Added below code into the top of the generate_excel.php
file.
include_once("connection.php"); $db = new dbObj(); $connString = $db->getConnstring(); $sql_query = "SELECT * FROM tasks"; $resultset = mysqli_query($connString, $sql_query) or die("database error:". mysqli_error($conn)); $tasks = array(); while( $rows = mysqli_fetch_assoc($resultset) ) { $tasks[] = $rows; }
Let’s create export features using PHP and export data into excel. We’ll also force the to browser download the file instead of display it. We’ll add the below code into the generate_excel.php
file.
if(isset($_POST["ExportType"])) { switch($_POST["ExportType"]) { case "export-to-excel" : // Submission from $filename = "phpflow_data_export_".date('Ymd') . ".xls"; header("Content-Type: application/vnd.ms-excel"); header("Content-Disposition: attachment; filename=\"$filename\""); ExportFile($tasks); //$_POST["ExportType"] = ''; exit(); default : die("Unknown action : ".$_POST["action"]); break; } } function ExportFile($records) { $heading = false; if(!empty($records)) foreach($records as $row) { if(!$heading) { // display field/column names as a first row echo implode("\t", array_keys($row)) . "\n"; $heading = true; } echo implode("\t", array_values($row)) . "\n"; } exit; }
the code shown above, The switch case block will execute based on the parameter value and the method invoked.
Browsers are being forced to download an excel file.
Define html layout for display data in table and button to fire export-to-csv
action. Added below code into the index.php
file.
<?php include_once("generate_excel.php"); ?> <meta charset="UTF-8" /> <title>Simple Example of Export Excel file using PHP and MySQL</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap-theme.min.css" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script> <title>phpflow.com : Demo of export to excel file</title> <div id="container"> <div class="col-sm-6 pull-left"> <div class="well well-sm col-sm-12"> <div class="btn-group pull-right"> <button type="button" class="btn btn-info">Action</button> <button type="button" class="btn btn-info dropdown-toggle" data-toggle="dropdown"> <span class="caret"></span> <span class="sr-only">Toggle Dropdown</span> </button> <ul class="dropdown-menu" role="menu" id="export-menu"> <li id="export-to-excel"><a href="#">Export to excel</a></li> <li class="divider"></li> <li><a href="#">Other</a></li> </ul> </div> </div> <form action="generate_excel.php" method="post" id="export-form"> <input type="hidden" value="" id="hidden-type" name="ExportType" /> </form> <table id="" class="table table-striped table-bordered"> <tbody> <tr> <th>Name</th> <th>Status</th> <th>Priority</th> <th>Date</th> </tr> </tbody> <tbody> <?php foreach($tasks as $row):?> <tr> <td><?php echo $row ['Name']?></td> <td><?php echo $row ['Status']?></td> <td><?php echo $row ['Priority']?></td> <td><?php echo $row ['Date']?></td> </tr> <?php endforeach; ?> </tbody> </table> </div> </div>
We’ve imported the ‘generate_excel.php’ file at the top of the code, which will yield task data for display in the HTML table. We’ve established a dropwodn with a ‘export to excel’ option. All task data will be displayed in an HTML table.
We’ve included a dropdown and need to catch and fire events so that when a user selects an option, the form is submitted. We’ll paste the code below at the bottom of the index.php
file.
<script type="text/javascript"> $(document).ready(function() { jQuery('#Export to excel').bind("click", function() { var target = $(this).attr('id'); switch(target) { case 'export-to-excel' : $('#hidden-type').val(target); //alert($('#hidden-type').val()); $('#export-form').submit(); $('#hidden-type').val(''); break } }); }); </script>
I hope it helps you!.
This tutorial helps integrate a PHP SDK with Laravel. We'll install aws-php-sdk into laravel application and access all aws services… Read More
in this quick PHP tutorial, We'll discuss php_eol with examples. PHP_EOL is a predefined constant in PHP and represents an… Read More
This Laravel tutorial helps to understand table Relationships using Elequonte ORM. We'll explore laravel table Relationships usage and best practices… Read More
We'll explore different join methods of Laravel eloquent with examples. The join helps to fetch the data from multiple database… Read More
in this Laravel tutorial, We'll explore valet, which is a development environment for macOS minimalists. It's a lightweight Laravel development… Read More
I'll go through how to use soft delete in Laravel 10 in this post. The soft deletes are a method… Read More
View Comments
Dear friend this is more like csv format, excel format contains many features like formatting ,auto calculations ..etc.
You should use open source excel libraries for that.
Regards,
Kaustubh
Yes you r right but if you want your custom features then you need your own created lib.
Great!
thank you very much ...
Thank You very much
Worked from me thanks.....
Your welcm
this code downloading full page
i want to download particular array in excel. what can i do for that..kindluy help me
do you need export particular index or row?currently code export an array of records
Thank you very much.
Please help me fix this link, i can not download it. Thank
You need to share this article using social buttons after that download button enable.
its just showing data in firebug.not able to download Excel
i am checking demo on chrome v55 and its working fine.
same problem, showing data but downloading
i verified code and found fine, can u plz send ur code into email to find error.
thank you so much !!!
it was really helpful