Export from php mysql to excel

I’m trying to get my MySQL data to Excel file, but I’m having problems with Excel cells. All my text goes to one cell, I would like to have each row value in separate Excel cell. Here is my code:

$queryexport = ("
SELECT username,password,fullname FROM ecustomer_users
WHERE fk_customer='".$fk_customer."'
");

$row = mysql_fetch_assoc($queryexport);

$result = mysql_query($queryexport);
$header = '';

for ($i = 0; $i < $count; $i++){
   $header .= mysql_field_name($result, $i)."t";
   }

while($row = mysql_fetch_row($result)){
   $line = '';
   foreach($row as $value){
          if(!isset($value) || $value == ""){
                 $value = "t";
          }else{
                 $value = str_replace('"', '""', $value);
                 $value = '"' . $value . '"' . "t";
                 }
          $line .= $value;
          }
   $data .= trim($line)."n";
   $data = str_replace("r", "", $data);

if ($data == "") {
   $data = "nno matching records foundn";
   }
}
header("Content-type: application/vnd.ms-excel; name='excel'");
header("Content-Disposition: attachment; filename=exportfile.xls");
header("Pragma: no-cache");
header("Expires: 0");

// output data
echo $header."n".$data;

mysql_close($conn);`

Naresh's user avatar

Naresh

2,73110 gold badges45 silver badges78 bronze badges

asked Mar 29, 2013 at 7:40

marc_s's user avatar

3

Just Try With The Following :

PHP Part :

<?php
/*******EDIT LINES 3-8*******/
$DB_Server = "localhost"; //MySQL Server    
$DB_Username = "username"; //MySQL Username     
$DB_Password = "password";             //MySQL Password     
$DB_DBName = "databasename";         //MySQL Database Name  
$DB_TBLName = "tablename"; //MySQL Table Name   
$filename = "excelfilename";         //File Name
/*******YOU DO NOT NEED TO EDIT ANYTHING BELOW THIS LINE*******/    
//create MySQL connection   
$sql = "Select * from $DB_TBLName";
$Connect = @mysql_connect($DB_Server, $DB_Username, $DB_Password) or die("Couldn't connect to MySQL:<br>" . mysql_error() . "<br>" . mysql_errno());
//select database   
$Db = @mysql_select_db($DB_DBName, $Connect) or die("Couldn't select database:<br>" . mysql_error(). "<br>" . mysql_errno());   
//execute query 
$result = @mysql_query($sql,$Connect) or die("Couldn't execute query:<br>" . mysql_error(). "<br>" . mysql_errno());    
$file_ending = "xls";
//header info for browser
header("Content-Type: application/xls");    
header("Content-Disposition: attachment; filename=$filename.xls");  
header("Pragma: no-cache"); 
header("Expires: 0");
/*******Start of Formatting for Excel*******/   
//define separator (defines columns in excel & tabs in word)
$sep = "t"; //tabbed character
//start of printing column names as names of MySQL fields
for ($i = 0; $i < mysql_num_fields($result); $i++) {
echo mysql_field_name($result,$i) . "t";
}
print("n");    
//end of printing column names  
//start while loop to get data
    while($row = mysql_fetch_row($result))
    {
        $schema_insert = "";
        for($j=0; $j<mysql_num_fields($result);$j++)
        {
            if(!isset($row[$j]))
                $schema_insert .= "NULL".$sep;
            elseif ($row[$j] != "")
                $schema_insert .= "$row[$j]".$sep;
            else
                $schema_insert .= "".$sep;
        }
        $schema_insert = str_replace($sep."$", "", $schema_insert);
        $schema_insert = preg_replace("/rn|nr|n|r/", " ", $schema_insert);
        $schema_insert .= "t";
        print(trim($schema_insert));
        print "n";
    }   
?>

I think this may help you to resolve your problem.

answered Mar 29, 2013 at 9:06

John Peter's user avatar

John PeterJohn Peter

2,8703 gold badges26 silver badges45 bronze badges

13

Try this code. It’s definitly working.

<?php
// Connection 

$conn=mysql_connect('localhost','root','');
$db=mysql_select_db('excel',$conn);

$filename = "Webinfopen.xls"; // File Name
// Download file
header("Content-Disposition: attachment; filename="$filename"");
header("Content-Type: application/vnd.ms-excel");
$user_query = mysql_query('select name,work from info');
// Write data to file
$flag = false;
while ($row = mysql_fetch_assoc($user_query)) {
    if (!$flag) {
        // display field/column names as first row
        echo implode("t", array_keys($row)) . "rn";
        $flag = true;
    }
    echo implode("t", array_values($row)) . "rn";
}
?>

answered Nov 18, 2014 at 5:38

Dileep kurahe's user avatar

5

If you just want your query data dumped into excel I have to do this frequently and using an html table is a very simple method. I use mysqli for db queries and the following code for exports to excel:

header("Content-Type: application/xls");    
header("Content-Disposition: attachment; filename=filename.xls");  
header("Pragma: no-cache"); 
header("Expires: 0");


echo '<table border="1">';
//make the column headers what you want in whatever order you want
echo '<tr><th>Field Name 1</th><th>Field Name 2</th><th>Field Name 3</th></tr>';
//loop the query data to the table in same order as the headers
while ($row = mysqli_fetch_assoc($result)){
    echo "<tr><td>".$row['field1']."</td><td>".$row['field2']."</td><td>".$row['field3']."</td></tr>";
}
echo '</table>';

answered Jan 27, 2017 at 16:42

RLytle's user avatar

RLytleRLytle

1211 silver badge5 bronze badges

2

This is new version of php code

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "your_dbname";
//mysql and db connection

$con = new mysqli($servername, $username, $password, $dbname);

if ($con->connect_error) {  //error check
    die("Connection failed: " . $con->connect_error);
}
else
{

}


$DB_TBLName = "your_table_name"; 
$filename = "excelfilename";  //your_file_name
$file_ending = "xls";   //file_extention

header("Content-Type: application/xls");    
header("Content-Disposition: attachment; filename=$filename.'.'.$file_ending");  
header("Pragma: no-cache"); 
header("Expires: 0");

$sep = "t";

$sql="SELECT * FROM $DB_TBLName"; 
$resultt = $con->query($sql);
while ($property = mysqli_fetch_field($resultt)) { //fetch table field name
    echo $property->name."t";
}

print("n");    

while($row = mysqli_fetch_row($resultt))  //fetch_table_data
{
    $schema_insert = "";
    for($j=0; $j< mysqli_num_fields($resultt);$j++)
    {
        if(!isset($row[$j]))
            $schema_insert .= "NULL".$sep;
        elseif ($row[$j] != "")
            $schema_insert .= "$row[$j]".$sep;
        else
            $schema_insert .= "".$sep;
    }
    $schema_insert = str_replace($sep."$", "", $schema_insert);
    $schema_insert = preg_replace("/rn|nr|n|r/", " ", $schema_insert);
    $schema_insert .= "t";
    print(trim($schema_insert));
    print "n";
}

answered Apr 11, 2017 at 6:31

A.A Noman's user avatar

A.A NomanA.A Noman

5,2069 gold badges26 silver badges46 bronze badges

1

I think you should try with this API

http://code.google.com/p/php-excel/source/browse/trunk/php-excel.class.php

With This

Create a quick export from a database table into Excel

Compile some statistical records with a few calculations and deliver
the result in an Excel worksheet

Gather the items off your (web-based) todo list, put them in a
worksheet and use it as a foundation for some more statistics
magic.**

answered Mar 29, 2013 at 8:05

Naresh's user avatar

NareshNaresh

2,73110 gold badges45 silver badges78 bronze badges

Try this code:

<?php
    header("Content-type: application/vnd-ms-excel");

    header("Content-Disposition: attachment; filename=hasil-export.xls");

    include 'view-lap.php';
?>

Spooky's user avatar

Spooky

2,9668 gold badges27 silver badges41 bronze badges

answered Oct 31, 2013 at 21:17

Jek Tv's user avatar

0

try this code

data.php

    <table border="1">
<tr>
    <th>NO.</th>
    <th>NAME</th>
    <th>Major</th>
</tr>
<?php
//connection to mysql
mysql_connect("localhost", "root", ""); //server , username , password
mysql_select_db("codelution");

//query get data
$sql = mysql_query("SELECT * FROM student ORDER BY id ASC");
$no = 1;
while($data = mysql_fetch_assoc($sql)){
    echo '
    <tr>
        <td>'.$no.'</td>
        <td>'.$data['name'].'</td>
        <td>'.$data['major'].'</td>
    </tr>
    ';
    $no++;
}
?>

code for excel file

export.php

<?php
// The function header by sending raw excel
header("Content-type: application/vnd-ms-excel");
// Defines the name of the export file "codelution-export.xls"
header("Content-Disposition: attachment; filename=codelution-export.xls");
// Add data table
include 'data.php';
?>

if mysqli version

$sql="SELECT * FROM user_details";
$result=mysqli_query($conn,$sql);
if(mysqli_num_rows($result) > 0)
{
    $no = 1;
            while($data = mysqli_fetch_assoc($result))
            {echo '
    <tr>
        <<td>'.$no.'</td>
        <td>'.$data['name'].'</td>
        <td>'.$data['major'].'</td>

    </tr>
    ';
    $no++;

http://codelution.com/development/web/easy-ways-to-export-data-from-mysql-to-excel-with-php/

answered Nov 22, 2015 at 16:41

luvking's user avatar

You can export the data from MySQL to Excel by using this simple code.

<?php
include('db_con.php');


$stmt=$db_con->prepare('select * from books');
$stmt->execute();


$columnHeader ='';
$columnHeader = "Sr NO"."t"."Book Name"."t"."Book Author"."t"."Book 
ISBN"."t";


$setData='';

while($rec =$stmt->FETCH(PDO::FETCH_ASSOC))
{
 $rowData = '';
 foreach($rec as $value)
 {
  $value = '"' . $value . '"' . "t";
  $rowData .= $value;
 }
 $setData .= trim($rowData)."n";
}


header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=Book record 
sheet.xls");
header("Pragma: no-cache");
header("Expires: 0");

echo ucwords($columnHeader)."n".$setData."n";

?>

complete code here php export to excel

answered Feb 20, 2018 at 8:46

Ehtesham Shami's user avatar

Posts by John Peter and Dileep kurahe helped me to develop what I consider as being a simpler and cleaner solution, just in case anyone else is still looking. (I am not showing any database code because I actually used a $_SESSION variable.)

The above solutions invariably caused an error upon loading in Excel, about the extension not matching the formatting type. And some of these solutions create a spreadsheet with the data across the page in columns where it would be more traditional to have column headings and list the data down the rows. So here is my simple solution:

$filename = "webreport.csv";
header("Content-Type: application/xls");    
header("Content-Disposition: attachment; filename=$filename");  
header("Pragma: no-cache"); 
header("Expires: 0");
foreach($results as $x => $x_value){
    echo '"'.$x.'",' . '"'.$x_value.'"' . "rn";
}
  1. Change to .csv (which Excel instantly updates to .xls and there is no error upon loading.)
  2. Use the comma as delimiter.
  3. Double quote the Key and Value to escape any commas in the data.
  4. I also prepended column headers to $results so the spreadsheet looked even nicer.

answered Feb 29, 2016 at 23:24

Trialsman's user avatar

TrialsmanTrialsman

3293 silver badges14 bronze badges

Try the Following Code Please.
just only update two values.
1.your_database_name
2.table_name

 <?php
    $host="localhost";
    $username="root";
    $password="";
    $dbname="your_database_name";
    $con = new mysqli($host, $username, $password,$dbname); 

        $sql_data="select * from table_name";
        $result_data=$con->query($sql_data);
        $results=array();
    filename = "Webinfopen.xls"; // File Name
    // Download file
    header("Content-Disposition: attachment; filename="$filename"");
    header("Content-Type: application/vnd.ms-excel");

    $flag = false;
    while ($row = mysqli_fetch_assoc($result_data)) {
        if (!$flag) {
            // display field/column names as first row
            echo implode("t", array_keys($row)) . "rn";
            $flag = true;
        }
        echo implode("t", array_values($row)) . "rn";
    }
    ?>

answered Dec 17, 2016 at 18:22

Samir Lakhani's user avatar

This is baes on John Peter’s answer above. The code is working perfectly but I needed it for WordPress. So, I did something like this:

<?php

require '../../../wp-load.php';

$file_name = "registered-users";
$args = array( 'role' => 'client',
   'meta_query' => array( array(
       'key' => '_dt_transaction_archived',
       'compare' => 'NOT EXISTS'
   ) ),
   'order' => 'DESC',
   'orderby' => 'ID'
);
$users = get_users( $args );
$file_ending = "xls";

// Header info for browser
header( "Content-Type: application/xls" );
header( "Content-Disposition: attachment; filename=$file_name.$file_ending" );
header( "Pragma: no-cache" );
header( "Expires: 0" );

/*******Start of Formatting for Excel*******/

// define separator (defines columns in excel & tabs in word)
$sep = "t"; //tabbed character
// start of printing column names as names of MySQL fields

print( "First Name" . $sep );
print( "Last Name" . $sep );
print( "E-Mail" . $sep );
print( "n" );
// end of printing column names

// start foreach loop to get data
$schema_insert = "";

foreach ($users as $user) {
    if ( $user ) {
        $schema_insert = "$user->first_name" . $sep;
        $schema_insert .= "$user->last_name" . $sep;
        $schema_insert .= "$user->user_email" . $sep;
        print "n";
        $schema_insert = str_replace( $sep . "$", "", $schema_insert );
        $schema_insert = preg_replace( "/rn|nr|n|r/", " ", $schema_insert );
        $schema_insert .= "t";
        print( trim( $schema_insert ) );
    }
}

answered Apr 16, 2021 at 7:16

Dragi Postolovski's user avatar

Recently I published an article How to Read CSV and Excel File in PHP Using PhpSpreadsheet.  One of the readers asked how to use PhpSpreadsheet to export MySQL database records to the Excel file. The user may need their MySQL data in the Excel or CSV file to read or share it easily. In this article, we discussed how one can export data from a database to Excel and CSV files. In addition to this, we will also study how one can send this exported file as an attachment in the email.

Getting Started

For getting started, you first need to install the PhpSpreadsheet library. I recommend using Composer for the installation of the library. Open the terminal in your project root directory and run the command:

composer require phpoffice/phpspreadsheet

PhpSpreadsheet is the library that provides support for reading and writing different types of file formats. Below is the screenshot of supported file formats.

File Supported

Our end goal is exporting database table records to the Excel/CSV file. For this, we require a few entries in our database. As an example, I am creating the ‘products’ table by running the below SQL query.

CREATE TABLE `products` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `product_name` varchar(255) NOT NULL,
 `product_sku` varchar(255) NOT NULL,
 `product_price` varchar(255) NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Next, add some dummy entries in the table so you will see a few records in the exported file.

INSERT INTO `products` (`product_name`, `product_sku`, `product_price`) VALUES
('Apple', 'app_111', '$1000'),
('Lenovo', 'len_222', '$999'),
('Samsung', 'sam_689', '$1200'),
('Acer', 'ace_620', '$900');

After this create a config.php file where we write the code for database connection.

config.php

<?php
$db_host = 'DATABASE_HOST';
$db_username = 'DATABASE_USERNAME';
$db_password = 'DATABASE_PASSWORD';
$db_name = 'DATABASE_NAME';
 
$db = new mysqli($db_host, $db_username, $db_password, $db_name);
 
if($db->connect_error){
    die("Unable to connect database: " . $db->connect_error);
}

Make sure to replace the placeholders with the actual values in the above code. This file will be included later to fetch records from the ‘products’ table.

In the next part of the tutorial, I am allocating a separate section for exporting data to Excel, exporting data to CSV, and sending the email with an exported file as an attachment.

Export MySQL Database Data to Excel Using PHP

You have installed the library and also have a database table with few entries. Now you can go ahead and write the actual code which will export an Excel file with data filled in it.

Create a <code>export-to-excel.php</code> file in the root directory. In this file, I will write a SQL query to fetch data from the database, write this data to Excel, and finally send the Excel file to the browser to download automatically.

export-to-excel.php

<?php
require_once "vendor/autoload.php";
require_once "config.php";
 
use PhpOfficePhpSpreadsheetSpreadsheet;
use PhpOfficePhpSpreadsheetWriterXlsx;
 
$spreadsheet = new Spreadsheet();
$Excel_writer = new Xlsx($spreadsheet);
 
$spreadsheet->setActiveSheetIndex(0);
$activeSheet = $spreadsheet->getActiveSheet();
 
$activeSheet->setCellValue('A1', 'Product Name');
$activeSheet->setCellValue('B1', 'Product SKU');
$activeSheet->setCellValue('C1', 'Product Price');
 
$query = $db->query("SELECT * FROM products");
 
if($query->num_rows > 0) {
    $i = 2;
    while($row = $query->fetch_assoc()) {
        $activeSheet->setCellValue('A'.$i , $row['product_name']);
        $activeSheet->setCellValue('B'.$i , $row['product_sku']);
        $activeSheet->setCellValue('C'.$i , $row['product_price']);
        $i++;
    }
}
 
$filename = 'products.xlsx';
 
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename='. $filename);
header('Cache-Control: max-age=0');
$Excel_writer->save('php://output');

When you run this code on the browser, an Excel file will be downloaded automatically and the Excel sheet will have the following entries.

Excel

Export MySQL Database Data to CSV Using PHP

In the previous section, we exported data to an Excel file. If someone is looking to export data in a CSV file then you need to change a few lines in the above code.

export-to-csv.php

<?php
require_once "vendor/autoload.php";
require_once "config.php";
 
use PhpOfficePhpSpreadsheetSpreadsheet;
use PhpOfficePhpSpreadsheetWriterCsv;
 
$spreadsheet = new Spreadsheet();
$Excel_writer = new Csv($spreadsheet);
 
$spreadsheet->setActiveSheetIndex(0);
$activeSheet = $spreadsheet->getActiveSheet();
 
$activeSheet->setCellValue('A1', 'Product Name');
$activeSheet->setCellValue('B1', 'Product SKU');
$activeSheet->setCellValue('C1', 'Product Price');
 
$query = $db->query("SELECT * FROM products");
 
if($query->num_rows > 0) {
    $i = 2;
    while($row = $query->fetch_assoc()) {
        $activeSheet->setCellValue('A'.$i , $row['product_name']);
        $activeSheet->setCellValue('B'.$i , $row['product_sku']);
        $activeSheet->setCellValue('C'.$i , $row['product_price']);
        $i++;
    }
}
 
$filename = 'products.csv';
 
header('Content-Type: application/text-csv');
header('Content-Disposition: attachment;filename='. $filename);
header('Cache-Control: max-age=0');
$Excel_writer->save('php://output');

Send an Email with File as an Attachment

We have seen how to download the file with data in Excel/CSV format. Some users may want to send the exported file as an attachment in the email. Let’s see how to achieve it.

First, install the PHPMailer library using the command:

composer require phpmailer/phpmailer

After installing the library, you can use any SMTP server to send an email. It’s up to you. You may use your hosting SMTP server, AWS SES, or Gmail SMTP server. If you are going with the Gmail SMTP server read our article Send Email Using Gmail SMTP Server from PHP Script which explains the configuration needed for it.

The previous code download Excel/CSV file automatically. But now, instead of making it downloadable, we will save the file in the directory and then send it as an attachment. In short, we will write the code below for saving the file.

...
...
$filename = 'products.csv';
 
if (!file_exists('files')) {
    mkdir('files', 0755);
}
$Excel_writer->save('files/'.$filename);

Our final code to send the attachment in an email will be as follows:

<?php
require_once "vendor/autoload.php";
require_once "config.php";
 
use PhpOfficePhpSpreadsheetSpreadsheet;
use PhpOfficePhpSpreadsheetWriterCsv;
 
//Import PHPMailer classes into the global namespace
use PHPMailerPHPMailerPHPMailer;
use PHPMailerPHPMailerException;
 
$spreadsheet = new Spreadsheet();
$Excel_writer = new Csv($spreadsheet);
 
$spreadsheet->setActiveSheetIndex(0);
$activeSheet = $spreadsheet->getActiveSheet();
 
$activeSheet->setCellValue('A1', 'Product Name');
$activeSheet->setCellValue('B1', 'Product SKU');
$activeSheet->setCellValue('C1', 'Product Price');
 
$query = $db->query("SELECT * FROM products");
 
if($query->num_rows > 0) {
    $i = 2;
    while($row = $query->fetch_assoc()) {
        $activeSheet->setCellValue('A'.$i , $row['product_name']);
        $activeSheet->setCellValue('B'.$i , $row['product_sku']);
        $activeSheet->setCellValue('C'.$i , $row['product_price']);
        $i++;
    }
}
 
$filename = 'products.csv';
 
if (!file_exists('files')) {
    mkdir('files', 0755);
}
$Excel_writer->save('files/'.$filename);
 
// send as an attachment
$mail = new PHPMailer(true);
try {
    $mail->isSMTP();
    $mail->Host = 'SMTP_HOST';
    $mail->SMTPAuth = true;
    $mail->Username = 'SMTP_USERNAME';   //username
    $mail->Password = 'SMTP_PASSWORD';   //password
    $mail->SMTPSecure = 'ssl';
    $mail->Port = 465;
 
    $mail->setFrom('FROM_EMAIL_ADDRESS', 'FROM_NAME');
    $mail->addAddress('RECEPIENT_EMAIL_ADDRESS', 'RECEPIENT_NAME');
 
    $mail->addAttachment('files/'.$filename);
 
    $mail->isHTML(true);
    $mail->Subject = 'Products Sheet';
    $mail->Body    = 'Products Sheet';
 
    $mail->send();
    echo 'Message has been sent';
} catch (Exception $e) {
    echo 'Message could not be sent. Mailer Error: '. $mail->ErrorInfo;
}

Replace the placeholders with the actual values and an email will be sent with an attachment to the recipient’s email address.

I hope you understand how to export MySQL database data to the Excel or CSV file and also send it as an attachment. Please share your thoughts and suggestions in the comment section below.

Related Articles

  • How to Transfer Files to Remote Server in PHP
  • Send Email Using Mailjet in PHP
  • How to Convert HTML to PDF in PHP

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

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,

  • Exporting Data to Excel with PHP and MySQL
  • Export Data to CSV and Download Using PHP and MySQL
  • Import CSV File Into MySql Using PHP
  • Export HTML Table Data to Excel, CSV, PNG and PDF using jQuery Plugin
  • Export the jQuery Datatable data to PDF,Excel,CSV and Copy

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

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.

<?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: %sn", mysqli_connect_error());
			exit();
		} 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.

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

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.

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.

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.

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

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' :
	$('#hidden-type').val(target);
	//alert($('#hidden-type').val());
	$('#export-form').submit();
	$('#hidden-type').val('');
	break
}
});
    });
</script>

Result:

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

Demo and Download source Code From Below Link

Если нужно быстро и единоразово выгрузить данные из таблицы MySQL в Exel файл, то помогут следующие способы:

1

Экспорт через PHPMyAdmin

В PHPMyAdmin при экспорте можно выбрать формат «CSV for MS Excel»:

Экспорт через PHPMyAdmin

При открытии полученного файла в Excel будет сбита кодировка:

Excel будет сбита кодировка

Чтобы это исправить, нужно открыть csv файл в редакторе типа Notepad++ и изменить кодировку на ANSI:

Notepad++ изменить кодировку на ANSI:

Результат:

2

Экспорт через HTML таблицу

Смысл метода состоит в том чтобы PHP-скриптом сформировать HTML таблицу:

<?php
$dbh = new PDO('mysql:dbname=db_name;host=localhost', 'логин', 'пароль');
$sth = $dbh->prepare("SELECT * FROM `test`");
$sth->execute();
$items = $sth->fetchAll(PDO::FETCH_ASSOC);
?>
		
<table>
	<tr>
		<td>ID</td>
		<td>Категория</td>
		<td>Название</td>
		<td>Описание</td>
	</tr>
	<?php foreach($items as $row): ?>
	<tr>
		<td><?php echo $row['id']; ?></td>
		<td><?php echo $row['category']; ?></td>
		<td><?php echo $row['name']; ?></td>
		<td><?php echo $row['text']; ?></td>
	</tr>
	<?php endforeach; ?>
</table>

PHP

Результат работы скрипта:

Полученную таблицу копируем и вставляем в чистый лист Microsoft Exel:

3

Экспорт через PHPExcel

Третий метод – сформировать xls-файл в библиотеке PHPExcel (PHPExcel.zip).

//spl_autoload_unregister('autoload');
require_once __DIR__ . '/PHPExcel/Classes/PHPExcel.php';
require_once __DIR__ . '/PHPExcel/Classes/PHPExcel/Writer/Excel2007.php';

$xls = new PHPExcel();
$xls->setActiveSheetIndex(0);
$sheet = $xls->getActiveSheet();

// Шапка
$sheet->getStyle("A1:D1")->getFont()->setBold(true);
$sheet->setCellValue("A1", 'ID');
$sheet->setCellValue("B1", 'Категория');
$sheet->setCellValue("C1", 'Название');
$sheet->setCellValue("D1", 'Описание');

// Выборка из БД
$dbh = new PDO('mysql:dbname=db_name;host=localhost', 'логин', 'пароль');
$sth = $dbh->prepare("SELECT * FROM `test`");
$items = $sth->fetch(PDO::FETCH_ASSOC);

$index = 2;
foreach ($items as $row) {
	$sheet->setCellValue("A" . $index, $row['id']);
	$sheet->setCellValue("B" . $index, $row['category']);
	$sheet->setCellValue("C" . $index, $row['name']);
	$sheet->setCellValue("D" . $index, $row['name']);
	$index++;
}

// Отдача файла в браузер
header("Expires: Mon, 1 Apr 1974 05:00:00 GMT");
header("Last-Modified: " . gmdate("D,d M YH:i:s") . " GMT");
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");
header("Content-type: application/vnd.ms-excel" );
header("Content-Disposition: attachment; filename=prods.xlsx");
 
$objWriter = new PHPExcel_Writer_Excel2007($xls);
$objWriter->save('php://output'); 

exit(); 

PHP

Результат:

Welcome to a quick tutorial on how to export data from MYSQL to an Excel Spreadsheet. Need to export some data from the database into Excel spreadsheets? Sadly, PHP is unable to generate Excel files natively.

To export data from MySQL to an Excel Spreadsheet:

  • We need to use a third-party library to generate Excel files in PHP, a good recommendation is PHPSpreadsheet.
  • Fetch entries from the database table.
  • Write them to a Spreadsheet using PHPSpreadsheet.

But just how is this done exactly? Let us walk through a simple example in this guide – Read on!

ⓘ I have included a zip file with the example code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

TLDR – QUICK SLIDES

Export MySQL To Excel Spreadsheet In PHP

Fullscreen Mode – Click Here

TABLE OF CONTENTS

DOWNLOAD & NOTES

First, here is the download link to the example source code as promised.

QUICK NOTES

  • A copy of PHPSpreadsheet is not included in the zip file. Download the latest version with Composer by yourself – composer require phpoffice/phpspreadsheet
  • Create a dummy database and import 2-database.sql.
  • Change the database settings in 3-db-spreadsheet.php to your own, and launch in the browser (or command line).

If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

DATABASE TO EXCEL SPREADSHEET

All right, let us now get into the example of how to export MYSQL data to an Excel spreadsheet.

STEP 1) DOWNLOAD PHPSPREADSHEET

Yep, PHP does not have native functions and extensions to generate Excel files, we will use a library called PHPSpreadsheet.

  • One of the lazy ways to get PHPSpreadsheet is to use a package manager called Composer. Just download and install that, quite a hassle, but a one-time effort nonetheless.
  • After installing Composer – Open the command line, navigate to your project folder, and run “composer require phpoffice/phpspreadsheet“.
  • That’s all, Composer will automatically fetch the latest version into the vendor/ project.

If you need more, the official manual for PhpSpreadsheet is available online here, and also check out their GitHub page.

STEP 2) CREATE A DUMMY DATABASE

2-database.sql

CREATE TABLE `users` (
  `id` bigint(20) NOT NULL,
  `name` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

ALTER TABLE `users`
  ADD PRIMARY KEY (`id`),
  ADD UNIQUE KEY `email` (`email`),
  ADD KEY `name` (`name`);
 
INSERT INTO `users` (`id`, `name`, `email`) VALUES
(1, 'John Doe', 'john@doe.com'),
(2, 'Jane Doe', 'jane@doe.com'),
(3, 'Apple Doe', 'apple@doe.com'),
...

For this example, we will be using this dummy user table. Very simple, and just has 3 fields – ID, name, and email.

STEP 3) EXPORT FROM DATABASE TO SPREADSHEET

3-db-spreadsheet.php

<?php
// (A) CONNECT TO DATABASE - CHANGE SETTINGS TO YOUR OWN!
$dbhost = "localhost";
$dbname = "test";
$dbchar = "utf8mb4";
$dbuser = "root";
$dbpass = "";
$pdo = new PDO(
  "mysql:host=$dbhost;charset=$dbchar;dbname=$dbname",
  $dbuser, $dbpass, [
  PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
  PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_NAMED
]);

// (B) LOAD PHPSPREADSHEET
require "vendor/autoload.php";
use PhpOfficePhpSpreadsheetSpreadsheet;
use PhpOfficePhpSpreadsheetWriterXlsx;

// (C) CREATE A NEW SPREADSHEET + WORKSHEET
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle("Users");
 
// (D) FETCH USERS + WRITE TO SPREADSHEET
$stmt = $pdo->prepare("SELECT * FROM `users`");
$stmt->execute();
$i = 1;
while ($row = $stmt->fetch()) {
  $sheet->setCellValue("A".$i, $row["id"]);
  $sheet->setCellValue("B".$i, $row["name"]);
  $sheet->setCellValue("C".$i, $row["email"]);
  $i++;
}

// (E) SAVE FILE
$writer = new Xlsx($spreadsheet);
$writer->save("users.xlsx");
echo "OK";

This should be pretty straightforward and easy to understand:

  1. Connect to the database, and remember to change the database settings to your own.
  2. Captain Obvious. Include and use the PHPSpreadsheet library.
  3. Create a new spreadsheet, and get the current worksheet.
  4. Fetch entries from the database and populate the cells.
  5. Save the spreadsheet onto the server (or force download if you want).

One small thing to take note though – Avoid exporting an entire database and not generate massive spreadsheets… That will probably crash the server.

ALTERNATIVE) EXPORT MYSQL TO CSV FILE

4-db-csv.php

<?php
// (A) CONNECT TO DATABASE - CHANGE SETTINGS TO YOUR OWN!
$dbhost = "localhost";
$dbname = "test";
$dbchar = "utf8mb4";
$dbuser = "root";
$dbpass = "";
$pdo = new PDO(
  "mysql:host=$dbhost;charset=$dbchar;dbname=$dbname",
  $dbuser, $dbpass, [
  PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
  PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_NAMED
]);
 
// (B) CSV HTTP HEADERS
header("Content-Type: text/csv");
header("Content-Disposition: attachment; filename="users.csv"");
 
// (C) GET ENTRIES + OUTPUT
$stream = fopen("php://output", "w");
$stmt = $pdo->prepare("SELECT * FROM `users`");
$stmt->execute();
while ($row = $stmt->fetch()) { fputcsv($stream, $row); }
fclose($stream);

If you do not want to use any extra libraries, we can always export them in CSV format instead. Just like the above, except that we are reading entries from the database and directly echoing them out.

LINKS & REFERENCES

  • A massive list of commonly used Excel formula that you might find useful.
  • Need to do the opposite of importing data from a spreadsheet instead? Here’s how – Import Excel into MySQL
  • Create Excel File In Javascript – Code Boxx

TUTORIAL VIDEO

INFOGRAPHIC CHEAT SHEET

Export MySQL To Excel Spreadsheet (Click To Enlarge)

THE END

Thank you for reading, and we have come to the end of this short tutorial. I hope this has helped you to create Excel files in PHP for your project, and if you have anything to share with this guide, please feel free to comment below. Good luck and happy coding!

This tutorial will learn you How to export Mysql data from web application to Excel file using PHP programming language. This functionality is mostly required in enterprise level web application. There are lots of data are transfer on daily basis and manage that into separate excel file. So, at that time this type of functionality is required in web application. This functionality reduce lots of time to take data into excel file.

In this simple post we have learn something regarding how to export data to Excel in PHP. If you have developed any project then that project you have to required this functionality like Exporting Data to Excel Sheet. So we have developed this tutorial, in which we have make simple PHP Script for Export Data from Web to Excel.

Online Demo

Name Address City Postal Code Country
Maria Anders Obere Str. 57 Berlin 12209 Germany
Ana Trujillo Avda. de la Construction 2222 Mexico D.F. 5021 Mexico
Antonio Moreno Mataderos 2312 Mexico D.F. 5023 Mexico
Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
Paula Parente Rua do Mercado, 12 Resende 08737-363 Brazil
Wolski Zbyszek ul. Filtrowa 68 Walla 01-012 Poland
Matti Karttunen Keskuskatu 45 Helsinki 21240 Finland
Karl Jablonski 305 — 14th Ave. S. Suite 3B Seattle 98128 USA
Paula Parente Rua do Mercado, 12 Resende 08737-363 Brazil

Source Code


<?php
$connect = mysqli_connect("localhost", "root", "", "testing");
$sql = "SELECT * FROM tbl_customer";  
$result = mysqli_query($connect, $sql);
?>
<html>  
 <head>  
  <title>Export MySQL data to Excel in PHP</title>  
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>  
 </head>  
 <body>  
  <div class="container">  
   <br />  
   <br />  
   <br />  
   <div class="table-responsive">  
    <h2 align="center">Export MySQL data to Excel in PHP</h2><br /> 
    <table class="table table-bordered">
     <tr>  
                         <th>Name</th>  
                         <th>Address</th>  
                         <th>City</th>  
       <th>Postal Code</th>
       <th>Country</th>
                    </tr>
     <?php
     while($row = mysqli_fetch_array($result))  
     {  
        echo '  
       <tr>  
         <td>'.$row["CustomerName"].'</td>  
         <td>'.$row["Address"].'</td>  
         <td>'.$row["City"].'</td>  
         <td>'.$row["PostalCode"].'</td>  
         <td>'.$row["Country"].'</td>
       </tr>  
        ';  
     }
     ?>
    </table>
    <br />
    <form method="post" action="export.php">
     <input type="submit" name="export" class="btn btn-success" value="Export" />
    </form>
   </div>  
  </div>  
 </body>  
</html>

export.php


<?php  
//export.php  
$connect = mysqli_connect("localhost", "root", "", "testing");
$output = '';
if(isset($_POST["export"]))
{
 $query = "SELECT * FROM tbl_customer";
 $result = mysqli_query($connect, $query);
 if(mysqli_num_rows($result) > 0)
 {
  $output .= '
   <table class="table" bordered="1">  
                    <tr>  
                         <th>Name</th>  
                         <th>Address</th>  
                         <th>City</th>  
       <th>Postal Code</th>
       <th>Country</th>
                    </tr>
  ';
  while($row = mysqli_fetch_array($result))
  {
   $output .= '
    <tr>  
                         <td>'.$row["CustomerName"].'</td>  
                         <td>'.$row["Address"].'</td>  
                         <td>'.$row["City"].'</td>  
       <td>'.$row["PostalCode"].'</td>  
       <td>'.$row["Country"].'</td>
                    </tr>
   ';
  }
  $output .= '</table>';
  header('Content-Type: application/xls');
  header('Content-Disposition: attachment; filename=download.xls');
  echo $output;
 }
}
?>

Export Data to Excel is a popular feature of web applications to allow dynamic data export to Excel file to save locally for further use. If you’re a PHP developer and thinking to implement data export to excel, then you’re here at right place. You will learn here how to implement data export to excel using PHP & MySQL.

In our previous tutorial you have learned how to export data to excel in CodeIgniter, now in this tutorial we will explain how to export data to excel with PHP and MySQL.

We will cover this tutorial step by step to create live demo to implement data export to excel with PHP and MySQL. You can also download complete source code of live.

Also, read:

  • Export Data to Excel with PhpSpreadsheet using CodeIgniter
  • Export Data to CSV File with PHP and MySQL
  • Export HTML Table Data to Excel, CSV and Text with jQuery, PHP and MySQL

So let’s start implementing data export to excel with PHP and MySQL. Before we begin, take a look on files structure for this example.

  • index.php:
  • export.php:

Step1: Create MySQL Database Table

As we will cover this tutorial with example to export data to Excel file, so first we will create MySQL database table developers to store developer records.

CREATE TABLE `developers` (
  `id` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `skills` varchar(255) NOT NULL,
  `address` varchar(255) NOT NULL,
  `gender` varchar(255) NOT NULL,
  `designation` varchar(255) NOT NULL,
  `age` int(11) NOT NULL,
  `image` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

We will also insert few records to this table.

INSERT INTO `developers` (`id`, `name`, `skills`, `address`, `gender`, `designation`, `age`, `image`) VALUES
(1, 'Smith', 'Java', 'Newyork', 'Male', 'Software Engineer', 34, 'image_1.jpg'),
(2, 'David', 'PHP', 'London', 'Male', 'Web Developer', 28, 'image_2.jpg'),
(3, 'Rhodes', 'jQuery', 'New Jersy', 'Male', 'Web Developer', 30, 'image_2.jpg'),
(4, 'Sara', 'JavaScript', 'Delhi', 'Female', 'Web Developer', 25, 'image_2.jpg'),
(5, 'Shyrlin', 'NodeJS', 'Tokiyo', 'Female', 'Programmer', 35, 'image_2.jpg'),
(6, 'Steve', 'Angular', 'London', 'Male', 'Web Developer', 28, 'image_2.jpg'),
(7, 'Cook', 'MySQL', 'Paris', 'Male', 'Web Developer', 26, 'image_2.jpg'),
(8, 'Root', 'HTML', 'Paris', 'Male', 'Web Developer', 28, 'image_2.jpg'),
(9, 'William', 'jQuery', 'Sydney', 'Male', 'Web Developer', 23, 'image_2.jpg'),
(10, 'Nathan', 'PHP', 'London', 'Male', 'Web Developer', 28, 'image_2.jpg'),
(11, 'Shri', 'PHP', 'Delhi', 'Male', 'Web Developer', 38, 'image_2.jpg'),
(12, 'Jay', 'PHP', 'Delhi, India', 'Male', 'Web Developer', 30, 'image_3.jpg');

Step2: Get Records from MySQL Database Table

In export.php file, we will get developer records from MySQL database table developers and store into an array.

include_once("db_connect.php");
$sqlQuery = "SELECT name, gender, age, skills, address, designation FROM developers LIMIT 10";
$resultSet = mysqli_query($conn, $sqlQuery) or die("database error:". mysqli_error($conn));
$developersData = array();
while( $developer = mysqli_fetch_assoc($resultSet) ) {
	$developersData[] = $developer;
}	

Step3: Display Records with Export to Excel Button

In index.php file, we will display developer records from $developersData array. We will also add data export button to export data.

<div class="container">		
	<div class="well-sm col-sm-12">
		<div class="btn-group pull-right">	
			<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post">					
				<button type="submit" id="dataExport" name="dataExport" value="Export to excel" class="btn btn-info">Export To Excel</button>
			</form>
		</div>
	</div>				  
	<table id="" class="table table-striped table-bordered">
		<tr>
			<th>Name</th>
			<th>Gender</th>
			<th>Age</th>
			<th>Skills</th>			
			<th>Address</th>
			<th>Designation</th>
		</tr>
		<tbody>
			<?php foreach($developersData as $developer) { ?>
			   <tr>
			   <td><?php echo $developer ['name']; ?></td>
			   <td><?php echo $developer ['gender']; ?></td>
			   <td><?php echo $developer ['age']; ?></td>  
				<td><?php echo $developer ['skills']; ?></td>			   
			   <td><?php echo $developer ['address']; ?></td>
			   <td><?php echo $developer ['designation']; ?></td>   
			   </tr>
			<?php } ?>
		</tbody>
    </table>		
</div>

Step4: Implement Data Export to Excel

Now we will implement export data to excel when export button clicked. We will use $developersData array for data exported and saved into an xlsx file.

<?php
if(isset($_POST["dataExport"])) {	
	$fileName = "webdamn_export_".date('Ymd') . ".xls";			
	header("Content-Type: application/vnd.ms-excel");
	header("Content-Disposition: attachment; filename="$fileName"");	
	$showColoumn = false;
	if(!empty($developersData)) {
	  foreach($developersData as $developerInfo) {
		if(!$showColoumn) {		 
		  echo implode("t", array_keys($developerInfo)) . "n";
		  $showColoumn = true;
		}
		echo implode("t", array_values($developerInfo)) . "n";
	  }
	}
	exit;  
}
?>

You may also like:

  • User Management System with PHP & MySQL
  • Datatables Add Edit Delete with Ajax, PHP & MySQL
  • Build Helpdesk System with jQuery, PHP & MySQL
  • Build Online Voting System with PHP & MySQL
  • School Management System with PHP & MySQL
  • DataTables Add Edit Delete with CodeIgniter
  • Create RESTful API using CodeIgniter
  • Build Reusable Captcha Script with PHP
  • Product Search Filtering using Ajax, PHP & MySQL
  • Image Upload and Crop in Modal with jQuery, PHP & MySQL
  • Build Push Notification System with PHP & MySQL
  • Project Management System with PHP and MySQL
  • Hospital Management System with PHP & MySQL
  • Build Newsletter System with PHP and MySQL
  • Skeleton Screen Loading Effect with Ajax and PHP
  • Build Discussion Forum with PHP and MySQL
  • Customer Relationship Management (CRM) System with PHP & MySQL
  • Online Exam System with PHP & MySQL
  • Expense Management System with PHP & MySQL

You can view the live demo from the Demo link and can download the script from the Download link below.
Demo Download

Export data feature is very useful where the data is saved on the local drive for offline uses. Export data to file functionality provides a user-friendly way to maintain a large number of data in the web application. There are various file formats are available to export data and download it as a file. Microsoft Excel is a widely used spreadsheet format that organizes and maintains data.

Generally, export data functionality is used in the data management section of the web application. Excel is the best format to export data in a file and you can easily export data to excel using PHP. In this tutorial, we will show you how to export data to Excel in PHP.

The example PHP script lets you integrate export data to excel functionality. With one click, the user can export data from the MySQL database to Excel and download it in MS Excel file format (.xls/.xlsx).

Export Data to Excel with PHP

In this example script, we will export data from the array (defined in the script) to an excel file.

The $data variable holds the data in array format which will be exported to Excel using PHP.

$data = array( 
    array(
"NAME" => "John Doe""EMAIL" => "john.doe@gmail.com""GENDER" => "Male""COUNTRY" => "United States"),
    array(
"NAME" => "Gary Riley""EMAIL" => "gary@hotmail.com""GENDER" => "Male""COUNTRY" => "United Kingdom"),
    array(
"NAME" => "Edward Siu""EMAIL" => "siu.edward@gmail.com""GENDER" => "Male""COUNTRY" => "Switzerland"),
    array(
"NAME" => "Betty Simons""EMAIL" => "simons@example.com""GENDER" => "Female""COUNTRY" => "Australia"),
    array(
"NAME" => "Frances Lieberman""EMAIL" => "lieberman@gmail.com""GENDER" => "Female""COUNTRY" => "United Kingdom")
);

The filterData() function is used to filter string before added to the excel sheet row.

function filterData(&$str){ 
    
$str preg_replace("/t/""\t"$str);
    
$str preg_replace("/r?n/""\n"$str);
    if(
strstr($str'"')) $str '"' str_replace('"''""'$str) . '"';
}

The following code helps to export data in excel and download it as a file.

  • The $fileName variable defines the name of the excel file.
  • The Content-Disposition and Content-Type headers force the excel file to download.
  • Run the loop through each key/value pair in the $data array.
  • Display column names as the first row using the $flag variable.
  • The PHP array_walk() function is used to filter the data together with filterData() function.
// Excel file name for download 
$fileName "codexworld_export_data-" date('Ymd') . ".xlsx"; // Headers for download
header("Content-Disposition: attachment; filename="$fileName"");
header("Content-Type: application/vnd.ms-excel"); $flag false;
foreach(
$data as $row) {
    if(!
$flag) {
        
// display column names as first row
        
echo implode("t"array_keys($row)) . "n";
        
$flag true;
    }
    
// filter data
    
array_walk($row'filterData');
    echo 
implode("t"array_values($row)) . "n";
}

exit;

Export Data from Database to Excel with PHP and MySQL

In this example script, we will export data from the MySQL database in an excel file using PHP.

Create Database Table:
For this example, we will create a members table with some basic fields in the MySQL database. The members table holds the records which will be exported to excel.

CREATE TABLE `members` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `first_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
  `last_name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
  `email` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `gender` enum('Male','Female') COLLATE utf8_unicode_ci NOT NULL,
  `country` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
  `created` datetime NOT NULL,
  `status` tinyint(1) NOT NULL DEFAULT 1 COMMENT '1=Active | 0=Inactive',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Database Configuration (dbConfig.php):
The following code is used to connect the database using PHP and MySQL. Specify the database host ($dbHost), username ($dbUsername), password ($dbPassword), and name ($dbName) as per your database credentials.

<?php 
// Database configuration
$dbHost     "localhost";
$dbUsername "root";
$dbPassword "root";
$dbName     "codexworld"; // Create database connection
$db = new mysqli($dbHost$dbUsername$dbPassword$dbName); // Check connection
if ($db->connect_error) {
    die(
"Connection failed: " $db->connect_error);
}

Export Data from Database:
The following code helps to export data from the MySQL database and download it as an excel file.

  • The filterData() function is used to filter string before added to the excel data row.
  • $fileName – Define the name of the excel file to be downloaded.
  • $fields – Define the column named of the excel sheet.
  • $excelData – Add the first row to the excel sheet as a column name.
  • Fetch member’s data from the database and add to the row of the excel sheet.
  • Define headers to force the file to download.
  • Render data of excel sheet.
<?php 
// Load the database configuration file
include_once 'dbConfig.php'; // Filter the excel data
function filterData(&$str){
    
$str preg_replace("/t/""\t"$str);
    
$str preg_replace("/r?n/""\n"$str);
    if(
strstr($str'"')) $str '"' str_replace('"''""'$str) . '"';
}
// Excel file name for download
$fileName "members-data_" date('Y-m-d') . ".xls"; // Column names
$fields = array('ID''FIRST NAME''LAST NAME''EMAIL''GENDER''COUNTRY''CREATED''STATUS'); // Display column names as first row
$excelData implode("t"array_values($fields)) . "n"; // Fetch records from database
$query $db->query("SELECT * FROM members ORDER BY id ASC");
if(
$query->num_rows 0){
    
// Output each row of the data
    
while($row $query->fetch_assoc()){
        
$status = ($row['status'] == 1)?'Active':'Inactive';
        
$lineData = array($row['id'], $row['first_name'], $row['last_name'], $row['email'], $row['gender'], $row['country'], $row['created'], $status);
        
array_walk($lineData'filterData');
        
$excelData .= implode("t"array_values($lineData)) . "n";
    }
}else{
    
$excelData .= 'No records found...'"n";
}
// Headers for download
header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename="$fileName""); // Render excel data
echo $excelData;

exit;

Export HTML Table Data to Excel using JavaScript

Conclusion

If you want to add an export option to the data list, the export to excel feature is perfect for it. With the export option, the user can download the data in an excel file and save it in a local drive. You can use this simple code to add export data functionality in the web application using PHP.

  • Excel
  • Export
  • MySQL
  • PHP

Are you want to get implementation help, or modify or enhance the functionality of this script? Click Here to Submit Service Request

If you have any questions about this script, submit it to our QA community — Ask Question

Like this post? Please share to your friends:
  • Exporting to excel from mysql
  • Export from excel to sharepoint
  • Export from excel to postgresql
  • Export from excel to json
  • Exporting to excel from asp net