How to exporting the MySql table data into excel sheet using php

In This article we are going to explaining about how to downloading or exporting the mysql table data into excel sheet format using PHP mysql. Here we take a table “users” from this table we will select all the data according to our mysql query and generate a excel file according to that data and we can also set a selected column name as the excel sheet header. We are using only PHP and Mysql to perform this action.

Right know almost every one developing a website that uses a database, they also requirement to store dynamic data in a table, whether that be contact form dynamic data such as posts, users, subscriber etc.

While that data can be easily extracted directly from the database using database software, but if you need to export that data using a web application then this downloading option is very important in web application. Using this code we can generate a report from our Mysql data. We can generate different type of Report from User Report, Admin Report or Leads Report etc. When anyone needs to generate any types of report, this code is very helpful.

Downloading or exporting mysql table data into excel sheet

<?php
define ("DB_HOST", "localhost");
define ("DB_USER", "root");
define ("DB_PASS", "");
define ("DB_NAME", "test");

$conn=mysqli_connect(DB_HOST, DB_USER, DB_PASS) or die(mysqli_error($conn));
mysqli_select_db($conn, DB_NAME) or die(mysqli_error($conn));

$setCounter = 0;
$setExcelName = "website_users_exl_file";

$setRec = mysql_query("SELECT first_name, last_name, email, dob FROM `users` ORDER BY id");

$setCounter = mysql_num_fields($setRec);
for ($i = 0; $i < $setCounter; $i++)
{
    $setMainHeader .= mysql_field_name($setRec, $i)."\t";
}

while($rec = mysql_fetch_row($setRec))
{
    $rowLine = '';
    foreach($rec as $value)
    {
        if(!isset($value) || $value == "")
        {
            $value = "\t";
        }
        else
        {
            $value = strip_tags(str_replace('"', '""', $value));
            $value = '"' . $value . '"' . "\t";
        }
        $rowLine .= $value;
    }
    $setData .= trim($rowLine)."\n";
}

$setData = str_replace("\r", "", $setData);

if ($setData == "")
{
    $setData = "\nno matching records found\n";
}

$setCounter = mysql_num_fields($setRec);

//This Header is used to make data download instead of display the data
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=".$setExcelName.".xls");
header("Pragma: no-cache");
header("Expires: 0");

//It will print all the Table row as Excel file row with selected column name as header.
echo ucwords($setMainHeader)."\n".$setData."\n";
?>

Custom exporting mysql table data into excel sheet

If you want to exporting mysql table data into excel sheet according to you want, using below code customize the code.

<?php
if($action == "export_excel_signup")
{
    $file_name = "registered_user_list".date("d-m-y").".xls";
    
    //This Header is used to make data download instead of display the data
    header("Content-Type: application/vnd.ms-excel");    
    header("Content-Disposition: attachment; filename=$file_name");
    header("Pragma: no-cache");
    header("Expires: 0");
    
    if($action == "export_excel_signup")
    {
        $sql = "SELECT first_name, last_name, email, dob FROM `users` ORDER BY id";
        $result = mysql_query($sql);
        $s_no = 1;
        $signup_details = "<table>
                           <tr>
                                <td>S.No</td>
                                <td>First Name</td>
                                <td>Last Name</td>
                                <td>Email</td>
                                <td>DOB</td>
                           </tr>";
        while($row = mysql_fetch_array($result))
        {
            $signup_details .= "
                           <tr>
                                <td>".$s_no."</td>
                                <td>".$row['first_name']."</td>
                                <td>".$row['last_name']."</td>
                                <td>".$row['email']."</td>
                                <td>".$row['dob']."</td>
                           </tr>";
            ++$s_no;
        }
        $signup_details .= "</table>";
        echo $signup_details;
    }
}
?>

Leave a Reply

Related Posts: You may like

How to remove whitespace from string using php

Remove All Special Characters From String PHP

Redirecting HTTP to HTTPS with PHP

Convert Base64 string to an image file

Tools:

Crypto Currency

PHPKIDA provides free online the best real-time crypto market price, news, predictions, index with graphs & historical data for 2000+ coins including bitcoin, ethereum, & altcoins from major cryptocurrency exchanges.

Visite Tool

Icon Generator

PHPKIDA provides free online icon generator. Our icon generator help you to edit, modify, resize and customize icon for your website and applications. Convert to a shap you like add icon border, you can change icon border color, border size, background color, icon shadow, icons color, icon size in your own way and save it as a png image.

Visite Tool

Youtube Video Downloader

PHPKIDA provides Free online YouTube video downloader to download YouTube videos quickly in MP4, 3GP, and more. Search your video and free fast download youtube videos.

Visite Tool

Sign up for weekly update

Milkshake is almost ready. If you're interested in testing it out, then sign up below to get exclusive access.