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
2,73110 gold badges45 silver badges78 bronze badges
asked Mar 29, 2013 at 7:40
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 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
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
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 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
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
2,9668 gold badges27 silver badges41 bronze badges
answered Oct 31, 2013 at 21:17
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
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
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";
}
- Change to .csv (which Excel instantly updates to .xls and there is no error upon loading.)
- Use the comma as delimiter.
- Double quote the Key and Value to escape any commas in the data.
- I also prepended column headers to
$results
so the spreadsheet looked even nicer.
answered Feb 29, 2016 at 23:24
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
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
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
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:
I hope its help you!.
Demo and Download source Code From Below Link
After putting so much effort into importing your data into an SQL
database and connecting it to your website, how do you get it back out
and into Excel in order to keep your off-line and on-line systems
synchronised?
The following article presents a simple method for downloading any
data from PHP into an Excel spreadsheet — or at least something that
looks like one.
What we’re actually doing here is creating a
text (TAB or CSV) file containing the data which can then be opened by
Excel or any other spreadsheet. Before you ask, that means NO
formatting, NO colours and NO formulae — just the actual data.
For maximum compatibility with recent version of Excel, Numbers and
other applications you should use the CSV
download format rather than tab-delimted text.
Preparing the data
The following examples use the dataset created for and earlier
article Sorting Arrays of Arrays which is
defined as follows:
<?PHP
$data = [
["firstname" => "Mary", "lastname" => "Johnson", "age" => 25],
["firstname" => "Amanda", "lastname" => "Miller", "age" => 18],
["firstname" => "James", "lastname" => "Brown", "age" => 31],
["firstname" => "Patricia", "lastname" => "Williams", "age" => 7],
["firstname" => "Michael", "lastname" => "Davis", "age" => 43],
["firstname" => "Sarah", "lastname" => "Miller", "age" => 24],
["firstname" => "Patrick", "lastname" => "Miller", "age" => 27]
];
?>
Further down this page you will find examples for creating a
downloadable file using data sourced from an SQL query.
The first step is to output the data in a tab-delimited format (CSV
can also be used but is slightly more complicated). To achieve this we
use the following code:
<?PHP
header("Content-Type: text/plain");
$flag = FALSE;
foreach($data as $row) {
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";
}
exit;
We set the content type to text/plain so that the output can
more easily be viewed in the browser. Otherwise, because there is no
HTML formatting, the output would appear as a single line of text.
The first line of output will be the column headings (in this case
the field names are used). Values are separated with a tab t
and rows with a line break n. The output should look
something like the following:
firstname lastname age
Mary Johnson 25
Amanda Miller 18
James Brown 31
Patricia Williams 7
Michael Davis 43
Sarah Miller 24
Patrick Miller 27
There’s already a weakness in this code that may not be immediately
obvious. What if one of the fields to be ouput already contains one or
more tab characters, or worse, a newline? That’s going to throw the
whole process out as we rely on those characters to indicate column- and
line-breaks.
The solution is to ‘escape’ the tab characters. In this case we’re
going to replace tabs with a literal t and line breaks with a
literal n so they don’t affect the formatting:
<?PHP
function cleanData(&$str)
{
$str = preg_replace("/t/", "\t", $str);
$str = preg_replace("/r?n/", "\n", $str);
}
header("Content-Type: text/plain");
$flag = FALSE;
foreach($data as $row) {
array_walk($row, __NAMESPACE__ . 'cleanData');
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";
}
exit;
The __NAMESPACE__ reference and are required
to be compatible with PHP
Namespaces, and should be included whether or not you are currently
using namespaces for your code to be future-compatible.
Before each row is echoed any tab characters are replaced
«t» so that our columns aren’t broken up. Also any line
breaks within the data are replaced with «n». Now, how to
set this up as a download…
Triggering a download
What many programmers don’t realise is that you don’t have to create
a file, even a temporary one, in order for one to be downloaded. It’s
sufficient to ‘mimic’ a download by passing the equivalent HTTP headers
followed by the data.
If we create a PHP file with the following code then when it’s called
a file will be downloaded which can be opened directly using Excel.
<?PHP
function cleanData(&$str)
{
$str = preg_replace("/t/", "\t", $str);
$str = preg_replace("/r?n/", "\n", $str);
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
}
// filename for download
$filename = "website_data_" . date('Ymd') . ".xls";
header("Content-Disposition: attachment; filename="$filename"");
header("Content-Type: application/vnd.ms-excel");
$flag = FALSE;
foreach($data as $row) {
array_walk($row, __NAMESPACE__ . 'cleanData');
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";
}
exit;
Note that we’ve added an extra line to the cleanData
function to detect double-quotes and escape any value that contains
them. Without this an uneven number of quotes in a string can confuse
Excel.
source
This should result in a file being downloaded and saved to your
computer. If all goes well then the filename will be
named «website_data_20230414.xls» and will open in Excel looking something like this:
How does it work? Setting the headers tells the browser to expect a
file with a given name and type. The data is then echoed, but instead
of appearing on the page it becomes the downloaded file.
Because of the .xls extension and the vnd.ms-excel file
type, most computers will associate it with Excel and double-clicking
will cause that program to open. You could also modify the file name
and mime type to indicate a different spreadsheet package or database
application.
There is no way to specify data/cell formatting, column widths,
etc, using this method. To include formatting try generating HTML code
or a script that actually builds an Excel file. Or create your own
macro in Excel that applies formatting after the import.
A similar technique can be used to allow users to download files that
have been uploaded previously using PHP and stored with different names.
More on that later…
Exporting from an SQL database
If your goal is to allow data to be exported from a query result
then the changes are relatively simple:
<?PHP
// Original PHP code by Chirp Internet: www.chirpinternet.eu
// Please acknowledge use of this code by including this header.
function cleanData(&$str)
{
$str = preg_replace("/t/", "\t", $str);
$str = preg_replace("/r?n/", "\n", $str);
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
}
// filename for download
$filename = "website_data_" . date('Ymd') . ".xls";
header("Content-Disposition: attachment; filename="$filename"");
header("Content-Type: application/vnd.ms-excel");
$flag = FALSE;
$result = pg_query("SELECT * FROM table ORDER BY field") or die('Query failed!');
while(FALSE !== ($row = pg_fetch_assoc($result))) {
array_walk($row, __NAMESPACE__ . 'cleanData');
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";
}
exit;
This is the entire script required to query the database, clean the
data, and trigger a file download.
The database functions need to match the database you’re using.
MySQL users for example will need to use mysqli_query
and either mysqli_fetch_assoc or mysqli_fetch_assoc in place of the PostgreSQL
functions. Or better, PDO::query().
For other databases see under User Comments
below or check the PHP documentation.
If you are seeing duplicate
columns (numbered as well as labeled) you need to change the fetch call
to return only the associative (ASSOC) array.
If you’re having trouble at this stage, remove the
Content-Disposition header and change the Content-Type back to
text/plain. This makes debugging a lot easier as you can see
the output in your browser rather than having to download and open the
generated file every time you edit the script.
Preventing Excel’s ridiculous auto-format
When importing from a text file as we’re essentially doing here,
Excel has a nasty habit of mangling dates, timestamps, phone numbers and
similar input values.
For our purposes, some simple additions to the cleanData
function take care of most of the problems:
<?PHP
// Original PHP code by Chirp Internet: www.chirpinternet.eu
// Please acknowledge use of this code by including this header.
function cleanData(&$str)
{
// escape tab characters
$str = preg_replace("/t/", "\t", $str);
// escape new lines
$str = preg_replace("/r?n/", "\n", $str);
// convert 't' and 'f' to boolean values
if($str == 't') $str = 'TRUE';
if($str == 'f') $str = 'FALSE';
// force certain number/date formats to be imported as strings
if(preg_match("/^0/", $str) || preg_match("/^+?d{8,}$/", $str) || preg_match("/^d{4}.d{1,2}.d{1,2}/", $str)) {
$str = "'$str";
}
// escape fields that include double quotes
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
}
?>
The section that prevents values being scrambled does so by inserting
an apostrophe at the start of the cell. When you open the resuling file
in Excel you may see the apostrophe, but editing the field will make it
disappear while retaining the string format. Excel is strange that way.
The types of values being escape this way are: values starting with a
zero; values starting with an optional + and at least 8
consecutive digits (phone numbers); and values starting with numbers in
YYYY-MM-DD format (timestamps). The relevant regular expressions have
been highlighted in the code above.
Exporting to CSV format
As newer versions of Excel are becoming fussy about opening files
with a .xls extension that are not actual Excel binary files, making CSV
format with a .csv extension is now a better option.
The tab-delimited text options describe above may be a bit limiting
if your data contains newlines or tab breaks that you want to preserve
when opened in Excel or another spreadsheet application.
A better format then is comma-separated variables (CSV) which can be
generated as follows:
<?PHP
// Original PHP code by Chirp Internet: www.chirpinternet.eu
// Please acknowledge use of this code by including this header.
function cleanData(&$str)
{
if($str == 't') $str = 'TRUE';
if($str == 'f') $str = 'FALSE';
if(preg_match("/^0/", $str) || preg_match("/^+?d{8,}$/", $str) || preg_match("/^d{4}.d{1,2}.d{1,2}/", $str)) {
$str = "'$str";
}
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
}
// filename for download
$filename = "website_data_" . date('Ymd') . ".csv";
header("Content-Disposition: attachment; filename="$filename"");
header("Content-Type: text/csv");
$out = fopen("php://output", 'w');
$flag = FALSE;
$result = pg_query("SELECT * FROM table ORDER BY field") or die('Query failed!');
while(FALSE !== ($row = pg_fetch_assoc($result))) {
array_walk($row, __NAMESPACE__ . 'cleanData');
if(!$flag) {
// display field/column names as first row
fputcsv($out, array_keys($row), ',', '"');
$flag = TRUE;
}
fputcsv($out, array_values($row), ',', '"');
}
fclose($out);
exit;
Normally the fputcsv command is used to write data in CSV
format to a separate file. In this script we’re tricking it into
writing directly to the page by telling it to write to
php://output instead of a regular file. A nice trick.
source
As an aside, to export directly to CSV format from the command line
interface in PostgreSQL you can use simply:
postgres=# COPY (SELECT * FROM table ORDER BY field) TO '/tmp/table.csv' WITH CSV HEADER;
and for MySQL, something like the following:
SELECT * FROM table ORDER BY field
INTO OUTFILE '/tmp/table.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY 'n'
Exporting to CSV with Unicode intact
If like us your data contains UTF-8 characters you will notice that
Excel doesn’t handle them very well. Other applications can open UTF-8
content without problems, but Microsoft apparently still occupies the
dark ages.
Fortunately, there is a trick you can use. Below you can see how we
modify the script to convert everything from UTF-8 to UTF-16 Lower
Endian (UTF-16LE) format which Excel, at least on Windows, will recognise.
When opening this file in Excel you might find all the data
bunched into the first column. This should be fixable using the
«Text to Columns…» command under the Data menu.
<?PHP
// Original PHP code by Chirp Internet: www.chirpinternet.eu
// Please acknowledge use of this code by including this header.
function cleanData(&$str)
{
if($str == 't') $str = 'TRUE';
if($str == 'f') $str = 'FALSE';
if(preg_match("/^0/", $str) || preg_match("/^+?d{8,}$/", $str) || preg_match("/^d{4}.d{1,2}.d{1,2}/", $str)) {
$str = "'$str";
}
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
$str = mb_convert_encoding($str, 'UTF-16LE', 'UTF-8');
}
// filename for download
$filename = "website_data_" . date('Ymd') . ".csv";
header("Content-Disposition: attachment; filename="$filename"");
header("Content-Type: text/csv; charset=UTF-16LE");
$out = fopen("php://output", 'w');
$flag = FALSE;
$result = pg_query("SELECT * FROM table ORDER BY field") or die('Query failed!');
while(FALSE !== ($row = pg_fetch_assoc($result))) {
array_walk($row, __NAMESPACE__ . 'cleanData');
if(!$flag) {
// display field/column names as first row
fputcsv($out, array_keys($row), ',', '"');
$flag = TRUE;
}
fputcsv($out, array_values($row), ',', '"');
}
fclose($out);
exit;
This script may not work for all versions of Excel. Please let us
know using the Feedback form below if you encounter problems or come up
with a better solution.
Changing column headings
The above database download examples all use the database field
names for the first row of the exported file which may not be what you
want. If you want to specify your own more user-friendly headings you
can modify the code as follow:
<PHP
$colnames = [
'memberno' => "Member No.",
'date_joined' => "Date joined",
'title' => "Title",
'firstname' => "First name",
'lastname' => "Last name",
'address' => "Address",
'postcode' => "Postcode",
'city' => "City",
'country' => "Country",
'phone' => "Telephone",
'mobile' => "Mobile",
'fax' => "Facsimile",
'email' => "Email address",
'notes' => "Notes"
];
function map_colnames($input)
{
global $colnames;
return isset($colnames[$input]) ? $colnames[$input] : $input;
}
// filename for download
$filename = "website_data_" . date('Ymd') . ".csv";
...
if(!$flag) {
// display field/column names as first row
$firstline = array_map(__NAMESPACE__ . 'map_colnames', array_keys($row));
fputcsv($out, $firstline, ',', '"');
$flag = TRUE;
}
...
?>
The values in the first row will be mapped according to the
$colnames associative array. If no mapping is provided for a
fieldname it will remain unchanged. Of course you will want to provide
your own list of suitable headings. They don’t have to be in order.
source
References
- Easy way to create XLS file from PHP
- Keeping leading zeros and large numbers
< PHP
Most recent 20 of 63 comments:
Post your comment or question
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