Home > Database > mysql > How to create excel file with mysql data using php code

How to create excel file with mysql data using php code

Hello friends, I have code for how to create a excel file with mysql data using php code. By following 5 steps to create excel file.We can implement it in admin section of websites for user list excel file.
PHP Solutions: Dynamic Web Design Made Easy

How to create excel file with mysql data using php code by Anil Kumar Panigrahi

How to create excel file with mysql data using php code by Anil Kumar Panigrahi

Follow the below steps to retrieve the data from database:


1) Connect to database:

$dbhost= "Mysql server name"; //your MySQL Server
$dbuser = "Username"; //your MySQL User Name
$dbpass = "password"; //your MySQL Password
$dbname = "database name";
//your MySQL Database Name of which database to use this
$tablename = "table"; //your MySQL Table Name which one you have to create excel file
// your mysql query here , we can edit this for your requirement
$sql = "Select * from $tablename ";
//create  code for connecting to mysql
$Connect = @mysql_connect($dbhost, $dbuser, $dbpass)
or die("Couldn't connect to MySQL:<br>" . mysql_error() . "<br>" . mysql_errno());
//select database
$Db = @mysql_select_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());


2) Define a filename of excel

//define separator (defines columns in excel & tabs in word)
$sep = "\t"; //tabbed character
$fp = fopen('database.xls', "w");
$schema_insert = "";
$schema_insert_rows = "";
//start of printing column names as names of MySQL fields


3) Set the column name of excel file

//start of adding column names as names of MySQL fields
for ($i = 1; $i < mysql_num_fields($result); $i++)
$schema_insert_rows.=mysql_field_name($result,$i) . "\t";
echo $schema_insert_rows;
fwrite($fp, $schema_insert_rows);
//end of adding column names


4) Getting data from database and adding to the excel file

//start while loop to get data
while($row = mysql_fetch_row($result))
//set_time_limit(60); //
$schema_insert = "";
for($j=1; $j<mysql_num_fields($result);$j++)
$schema_insert .= "NULL".$sep;
elseif ($row[$j] != "")
$schema_insert .= strip_tags("$row[$j]").$sep;
$schema_insert .= "".$sep;
$schema_insert = str_replace($sep."$", "", $schema_insert);

//this corrects output in excel when table fields contain \n or \r
//these two characters are now replaced with a space

$schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
$schema_insert .= "\n";
//$schema_insert = (trim($schema_insert));
//print $schema_insert .= "\n";
//print "\n";


5) After adding data to excel file is completed then close the file

fwrite($fp, $schema_insert);

This is the steps to create excel file with mysql data using php code.

You may also like
Multi-language support for web application with MySql and PHP
Simple Steps to Build a Custom CMS application Using PHP
How to add or remove file fields using jquery
How to calculate statistics in daily, weekly , monthly and yearly using php

28 Responses

  1. Pingback : How to create excel file with mysql data using php code « ANIL …

  2. You could always explain how to create a real Excel file rather than a simple tab-separated file. Yes, Excel can read tab- or comma-separated value files, as can many applications… giving that file an extension of .xls does not make it an Excel file.

    And if you do create a tab-separated file, don’t make it such complex code, with all kinds of unnecessary overhead: use PHP’s fputcsv() function which does the hard work for you. This has the advantage of escaping quotes and other special characters in your data, which your code doesn’t.

    If you want to create a real Excel file, which has the benefits of cell formatting, frozen heading rows, filter headings, and all the other features of Excel itself, then it can be done (using less code than your example) with one of the myriad of free PHP libraries such as PHPExcel.

  3. It could be not the ideal solutions but it works very good and it’s simple to understand.. I have been more than 2 hours reading other codes and they all included to download api and were more complicated when you use a shared hosting… so, this is short code, easy to understand and use, just copy and paste and it works… anyway when you download the file, Microsft Excel ask you to convert it to a good xls format, you say yes and your file is converted to a legitime excel without any problem…. I think this code is very practical.

    thanks to Anil..

  4. Hey all this code sure is great for a simple excel file creation and has worked for me , having said that is there any way we can format the output??? more precisely can i oput in bold text … please help if if u can … thank you!!

  5. All this did for me is display in the web page the column names in the database. No excel file and no content from the database other than the headings?

    What am I missing here?

  6. Pingback : Top 10 most viewed posts in anil labs - Anil Labs

  7. Thank You . i found the first field not appear to modfiy that you must make first $i value in loop is 0 instead of one so it should be like that for ($i = 0; $i < mysql_num_fields($result); $i++)

  8. hi…
    i want know the ………..
    how to create .xls file or software ….
    but step by step means which software or etc and another thing also 1 by 1 ok
    plz any1 spcly anil plz help yar plz………..

  9. xjshiya

    i want to put headers/title in my generated excel report. how can i customize the title/header like centering the title with bold text and underline? thanks in advance.

  10. Silpa Sadanandan

    It is a nice tutorial. I just want to make the excel file stored in a different location other than the project folder . Can you please suggest the code for that also?
    Thanks in advance

  11. Ayush

    Dude this is great
    But im getting duplicate values and also im using odbc connection instead of mysql_connect
    everything is working fine except for the duplicate values can u tell me how can i omit duplicate values thankx..

  12. meet

    hay this generates the excel sheet but not showing me any of data..just shows the column name..
    i have just copy paste your code…should i have to do modification inside it???

Leave a Reply

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