Exporting Data to Excel with PHP and MySQL

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.

Video Tutorial

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,

Export MySQL Data To Excel in 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.

So the file structure for this example is the following:

  • index.php: This is the entry file.
  • connection.php: This file is used to connect MySQL with PHP
  • generate_excel.php: This is the main PHP file that’ll have an export method to export data into the excel.

Create MySQL Database Table

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

-- Indexes for table `tasks`
-- AUTO_INCREMENT for table `tasks`

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');

Create MySQL Connection With PHP

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.

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());
		} else {
			$this->conn = $con;
		return $this->conn;

Get the Tasks Data from MySQL Database Table

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.

$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;

Export Data to Excel

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.

        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\"");
			//$_POST["ExportType"] = '';
        default :
            die("Unknown action : ".$_POST["action"]);
function ExportFile($records) {
	$heading = false;
		  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";

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.

Create HTML and Display Records with Export Button

Define html layout for display data in table and button to fire export-to-csv action. Added below code into the index.php file.


<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>

                <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>

        <form action="generate_excel.php" method="post" id="export-form">
            <input type="hidden" value="" id="hidden-type" name="ExportType" />

        <table id="" class="table table-striped table-bordered">



                <?php foreach($tasks as $row):?>

                    <td><?php echo $row ['Name']?></td>

                    <td><?php echo $row ['Status']?></td>

                    <td><?php echo $row ['Priority']?></td>

                    <td><?php echo $row ['Date']?></td>

                <?php endforeach; ?>

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.

Submit Form Using jQuery

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' :


export-to-excel with php and mysql
I hope its help you!.

Demo and Download source Code From Below Link

28 thoughts on “Exporting Data to Excel with PHP and MySQL

  1. 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.


  2. this code downloading full page
    i want to download particular array in excel. what can i do for that..kindluy help me

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.