Create excel files with php
Excel files are great for many things. It might though be a little bit tricky to generate them on the fly with php. Therefor I will guide you exactly how to do it, quick and simple.
Have you ever thought of creating excel files from your web site?
Excel is a very useful format for lots of purposes. For example, exporting stats, member lists to hand over to economy department etc.
But how can we create a simple excel file with a header and two different columns?
Of course you can sit down and read the excel specifications, and do it your self…
Or the smarter way, download classes from phpclasses.org made by Ignatius Teo.
You use these classes to generate your excel files. Pretty simple, but very effective.
Start with downloading (registrate for free to download), here http://www.phpclasses.org/browse/package/1919.html .
Unzip and upload the file named excel.php to your server.
I am going to generate a simple excel file that will contain Name and IQ in two columns ![]()
The file will look something like this (Hopefully):
First name IQ
Mattias 250
Tony 100
Peter 100
Edvard 100
(These numbers are just estimates…
Create the php file that will create the excel files for you.
Lets call it: generate.php
Start with:
require_once "excel.php"; $filename = "theFile.xls";
This section will create and save the excel file on the server.
The file will be saved in the directory tmp, as theFile.xls.
The code is pretty self explaining I think. don’t bother with small details, just use it as a tool!
$export_file = "xlsfile://tmp/".$filename;
$fp = fopen($export_file, "wb");
if (!is_resource($fp))
{
die("Cannot open $export_file");
}
// typically this will be generated/read from a database table
$assoc = array(
array("First name" => "Mattias", "IQ" => 250,
array("First name" => "Tony", "IQ" => 100,
array("First name" => "Peter", "IQ" => 100,
array("First name" => "Edvard", "IQ" => 100);
fwrite($fp, serialize($assoc));
fclose($fp);
This section is for opening the file directly for the surfer in his browser.
It’s then up to the user to choose if he/she wants to open or save the file.
If you only want to save files on the server, just remove this part from the file.
header ("Expires: Mon, 26 Jul 1997 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/x-msexcel");
header ("Content-Disposition: attachment; filename="" . $filename . """ );
header ("Content-Description: PHP/INTERBASE Generated Data" );
readfile($export_file);
exit;
If you run this code you will get two things:
- An excel file in /var/ on your server
- This file opened to the user that surf your site
This is the whole tutorial, showing you that it is not that hard to create an excel file or open it to the user ![]()
Good luck and let me know if you have any problems with the code!!

May 11th, 2009 at 2:13 pm
Thanks for sharing this but I guess it’s not a possible solution I you can’t modify extensions of my “shared” server, right?
May 11th, 2009 at 2:24 pm
Panamon Rn+: This class does not need to modify any extensions. So you just need to download the class and include it and use it in your script.
May 13th, 2009 at 11:32 pm
I added this page to Digg
May 14th, 2009 at 12:10 am
Learned lots, I will return
May 14th, 2009 at 4:11 am
I bookmarked this
May 14th, 2009 at 3:34 pm
Nice post, and a great blog you have here. I’ve been checking back a lot, but is there anyway to signup to the RSS feed?
May 15th, 2009 at 5:03 am
Hi, THanks
Can u tell me same 2 column excel file how to impore in MYSQL using PHP…..
Please
May 17th, 2009 at 10:20 am
Hi, Sorry but I don’t really understand what you are saying…
May 17th, 2009 at 10:22 am
Welcome to the blog! To signup to the RSS feed just click the blue RSS-icon or the text “grab our rss feed” at the top right of the site!
May 17th, 2009 at 10:23 am
Thanks guys! Glad to hear that you like the tutorials!
June 1st, 2009 at 10:56 am
Our servers now require PHP for interactive content (in the past I have used .cgi files). I’ve never used PHP and am
looking for a way to add entries to an existing Excel (or any)
file from a web-form.
It looks like your scripts may do this but I’m not sure 1)
what the form needs to look like and 2) if each new entry
will be added to the same file.
Can you give me some more details on how I might do this?
June 3rd, 2009 at 2:03 pm
Hi John,
I’m sorry buy I have no possibility to help you with that. I know that I have read somewhere about a new package that is capable to create excel files in a new way. so you will need to google to see if you can find it, because it’s not possible with this class. Good luck!
June 4th, 2009 at 12:12 am
how can we configure cell widths, bolded/underline text?
if cannot, we might as well generate a .csv instead?
June 4th, 2009 at 8:08 pm
Really insightful posts here. Glad I finally found this place. I can’t remember who referred me here, but sure glad they did.
June 8th, 2009 at 10:15 pm
hi,
I tested the provided code above but the output is different.
here is the code
“Mattias”, “IQ” => 250),
array(“First name” => “Tony”, “IQ” => 100),
array(“First name” => “Peter”, “IQ” => 100),
array(“First name” => “Edvard”, “IQ” => 100));
fwrite($fp, serialize($assoc));
fclose($fp);
?>
when i open it in excel the output is
a:4:{i:0;a:2:{s:10:”First name”;s:7:”Mattias”;s:2:”IQ”;i:250;}i:1;a:2:{s:10:”First name”;s:4:”Tony”;s:2:”IQ”;i:100;}i:2;a:2:{s:10:”First name”;s:5:”Peter”;s:2:”IQ”;i:100;}i:3;a:2:{s:10:”First
thanks
June 8th, 2009 at 10:17 pm
complete code
“Mattias”, “IQ” => 250),
array(“First name” => “Tony”, “IQ” => 100),
array(“First name” => “Peter”, “IQ” => 100),
array(“First name” => “Edvard”, “IQ” => 100));
fwrite($fp, serialize($assoc));
fclose($fp);
?>
June 16th, 2009 at 2:15 pm
The fopen statement fails, I get the message
[function.fopen]: failed to open stream: “xlsStream::stream_open” call failed
This happens on both local host and the actual website
June 17th, 2009 at 7:18 am
[...] sure it’d be a simple matter to do the same for Excel. A quick Google search turned up this page which describes how to do exactly what I need. The sheer number of people that write code in PHP [...]
July 6th, 2009 at 6:48 am
Thanks for a great script!
I’m having problem populating the array, from my MYSQL query.
Does anybody have a suggestion?
Thanks
Thomas
July 6th, 2009 at 6:52 am
Me again.
$assoc = array(
// I want to loop through the result set from my query, and
add the arrays below. Any suggestion would be appreciated.
array(”First name” => “Mattias”, “IQ” => 250,
array(”First name” => “Tony”, “IQ” => 100,
array(”First name” => “Peter”, “IQ” => 100,
array(”First name” => “Edvard”, “IQ” => 100);
July 10th, 2009 at 8:20 am
Tirso, you need to include the “xlsfile” in the directory of the file. Example:
$export_file = “xlsfile://Directory/Filename.xls”;
To loop through the result of MySQL. heres the sample code.
$arr = array();
$i = 0;
while ($row = mysql_fetch_array($query))
{
$arr[$i] = array(‘culumn1′ => ’sample data1′, ‘column2′ => ’sample data2′);
$i++;
}
$assoc = $arr;
fwrite($fp, serialize($assoc));
fclose($fp);
hope this helps
July 14th, 2009 at 6:31 am
Thanks Sugar Ray!!!
That really helped.
Thomas
July 15th, 2009 at 4:16 am
I have the same problem as Tirso. I’m getting the following when I open the excel file:
a:4:{i:0;a:2:{s:10:”First name”;s:7:”Mattias”;s:2:”IQ”;i:250;}i:1;a:2:{s:10:”First name”;s:4:”Tony”;s:2:”IQ”;i:100;}i:……
I am currently using this line:
$export_file = “tmp/Filename.xls”;
When i try using this line:
$export_file = “xlsfile://tmp/Filename.xls”;
I get: “Warning: fopen(xlsfile://tmp/Filename.xls) [function.fopen]: failed to open stream: “xlsStream::stream_open” call failed in E:\domains\s\sefeedback.co.uk\user\htdocs\functions\generate_training_report.php on line 6
Cannot open xlsfile://tmp/Filename.xls”
Please help!
July 28th, 2009 at 6:25 am
Dear All,
I have saved the excel.php in same path as the generate.php
I created an excel file in the following path C: and name it thisFile.xls
But when am running the generate.php am getting the following error
Cannot open xlsfile://C:/theFile.xlsPHP Warning: parse_url(xlsfile://C:/theFile.xls): Unable to parse url in D:\Documents and Settings\maheshwaree.panchoo\My Documents\php trial\excel.php on line 73 PHP Warning: fopen(xlsfile://C:/theFile.xls): failed to open stream: “xlsstream::stream_open” call failed in D:\Documents and Settings\maheshwaree.panchoo\My Documents\php trial\- on line 10
“Mattias”, “IQ” => 250),
array(“First name” => “Tony”, “IQ” => 100),
array(“First name” => “Peter”, “IQ” => 100),
array(“First name” => “Edvard”, “IQ” => 100));
fwrite($fp, serialize($assoc));
fclose($fp);
?>
kindly Help
Regards Cleopatra
Below is my code
July 28th, 2009 at 11:34 pm
“Mattias”, “IQ” => 250),
array(“First name” => “Tony”, “IQ” => 100),
array(“First name” => “Peter”, “IQ” => 100),
array(“First name” => “Edvard”, “IQ” => 100));
fwrite($fp, serialize($assoc));
fclose($fp);
?>
July 28th, 2009 at 11:35 pm
<?php
require_once "excel.php";
$filename = "theFile.xls";
//This section will create and save the excel file on the server.
//The file will be saved in the directory tmp, as theFile.xls.
//The code is pretty self explaining I think. don’t bother with small details, just use it as a tool!
$export_file ="xlsfile://C:/".$filename;
$fp = fopen($export_file, "wb");
if (!is_resource($fp))
{
die("Cannot open $export_file");
}
July 29th, 2009 at 6:00 am
Dear Thomas,
Can you please send me the full the code that u have to send the send result in excel through mysql.
Many thanks
Cleopatra
August 17th, 2009 at 11:33 am
Just some feedback – Some criteria, requirements must be missing in the directions.
When I use xlsfile:// nothing works, and when I remove it it just prints code into the document.
The document it self couldn’t be created, so I just put a empty ‘example.xls’ to satisfy the error. Pretty certain my folder permissions allow for file creation.
But at any rate somethings missing from the whole thing, and judging from the comments above I’m not the only one having issues.
Thanks though,
M
September 8th, 2009 at 6:15 am
Some of my Excel document has more than 1 line in a cell. I enter that using alt+enter in Excel. But if I were to ask the user to enter the data using a textarea, they would enter using the Enter key. If I store this in MySQL and want to export it as Excel document, how do i print the new lines in a single cell. Replacing new lines to chr(10) & chr(13) prints the 2nd line in a new row in Excel.
Thanx
Sid
September 8th, 2009 at 6:42 am
Haven’t had the chance to try it myself, but if you try to only user chr(10) OR chr(13)?
Don’t remember how the class works completely, but what happens if you user a html br? ()
September 11th, 2009 at 12:25 am
hello…the excel document is very interesting..nice one
but me i have want to generate an excel sheet from mysql.
I have 3tables in mysql and i must retrieve information from these tables and i have been able to do it without anyproblem.
the only problem that am facing is that in the excel at the header of the page, i must insert a logo or a picture of the company and at the footer i must put the company’s name, details and so on.
can anyone tell me how to import images in excel??
thanks in advance!!!!
September 11th, 2009 at 1:02 am
You can’t import images with this class into excel. But there is another way where you use html and export that into excel. I don’t have that information here, but I will try to create a tutorial later on the topic. There are better ways now to create excel files, so this tutorial is starting to get old… but still useful.
September 11th, 2009 at 5:29 am
Hi
Can you please explain how the path in “xlsfile://tmp” is to be specified exactly with an example?
I am getting following error:
Warning: fopen(xlsfile://to/example.xls) [function.fopen]: failed to open stream: “xlsStream::stream_open” call failed in C:\Program Files\EasyPHP 2.0b1\www\IPD\admin\example_export.php on line 13
Cannot open xlsfile://to/example.xls
Here the example.xls file is under the ‘to’ folder which is under the ‘admin’ folder containing the example_export.php file.
I am using Windows Vista so just wondering if UAC has got to do anything with this?
Kindly help people.
Thanks
September 11th, 2009 at 10:38 am
ok..thanks you
September 14th, 2009 at 5:52 am
Hi all,
Its really nice module, you have done great job, it takes 3 minutes for me from downloading the modules till successfully creating xyz.xls. reaplly amazing.
But i have one more problem.
Now the time is to read the .xls file using PHP.
I have used several modules that are available on internet. while reading using this code i get an uniform error message.
“The filename xyz.xls is not readable”.
Please tell me how and where i’ve to change the code.
Please reply.
September 23rd, 2009 at 5:09 am
hi ,
I’m getting the following when I open the excel file:
This is only happening in linux server. Any body Please help me
a:3:{i:0;a:5:{s:12:”Sales Person”;s:11:”Sam Jackson”;s:2:”Q1″;s:5:”$3255″;s:2:”Q2″;s:5:”$3167″;s:2:”Q3″;i:3245;s:2:”Q4″;i:3943;}i:1;a:5:{s:12:”Sales Person”;s:9:”Jim Brown”;s:2:”Q1″;s:5:”$2580″;s:2:”Q2″;s:5:”$2677″;s:2:”Q3″;i:3225;s:2:”Q4″;i:3410;}i:2;a:5:{s:12:”Sales Person”;s:12:”John Hancock”;s:2:”Q1″;s:5:”$9367″;s:2:”Q2″;s:5:”$9875″;s:2:”Q3″;i:9544;s:2:”Q4″;i:10255;}}
The below code i am using
require_once “excel.php”;
$export_file = “example”;
$appPath = preg_replace(“/([A-Za-z]:\/)/”, “xlsfile://”, eregi_replace(“\\\\”, ‘/’, dirname(__FILE__)),1);
$gen_file = $appPath.”/excel/$export_file.xls”;
// typically this will be generated/read from a database table
$myresult = array(
array(“Sales Person” => “Sam Jackson”, “Q1″ => “$3255″, “Q2″ => “$3167″, “Q3″ => 3245, “Q4″ => 3943),
array(“Sales Person” => “Jim Brown”, “Q1″ => “$2580″, “Q2″ => “$2677″, “Q3″ => 3225, “Q4″ => 3410),
array(“Sales Person” => “John Hancock”, “Q1″ => “$9367″, “Q2″ => “$9875″, “Q3″ => 9544, “Q4″ => 10255),
);
$fp = fopen($gen_file, “wb”);
fwrite($fp, serialize($myresult));
Any body Please help me
Thanks
Nagarjuna
October 7th, 2009 at 10:24 am
anybody solved the tw problems??
1) NOT having to create before hand an empty whatever.xls
2) NOT getting this:
a:3:{i:0;a:5:{s:12:”Sales Person”;s:11:”Sam Jackson”;s:2:”Q1″;s:5:”$3255″;s:2:”Q2″;s:5:”$3167″;s:2:”Q3″;i:3245;s:2:”Q4″;i:3943;}i:1;a:5:{s:12:”Sales Person”;s:9:”Jim Brown”;s:2:”Q1″;s:5:”$2580″;s:2:”Q2″;s:5:”$2677″;s:2:”Q3″;i:3225;s:2:”Q4″;i:3410;}i:2;a:5:{s:12:”Sales Person”;s:12:”John Hancock”;s:2:”Q1″;s:5:”$9367″;s:2:”Q2″;s:5:”$9875″;s:2:”Q3″;i:9544;s:2:”Q4″;i:10255;}}
thank you in advance!!
October 7th, 2009 at 10:55 am
Hi.
First of all, thanks for this post.
Second, I get an error when I run your first example, example_export.php:
Notice: Undefined variable: size in /var/www/…/httpdocs/php/excel.php on line 162
Then the Excel file looks like this:
Notice: Undefined variable: data in /var/www/…/httpdocs/php/excel.php on line 110
” Sales Person”
Q1
Q2
Q3
Q4Sam Jackson
$3255
$3167Z©@ŒÆ@ “ Jim Br” own
$2580
$26772©@§™@ John H ancock
$9367
$9875§¬@ă@
Notice: Undefined variable: data in /var/www/…/httpdocs/php/excel.php on line 113
All the files are in httpdocs/php/ on the server
Hope someone can help.
Thanks
October 7th, 2009 at 11:04 am
Hi
sorry to see that so many people are having problem with this.
Unfortunately i dont have the time right now to investigate it. But i promise à new tutorial with à brand new way to handle this. Much better and easier.
October 7th, 2009 at 12:34 pm
Fixed it.
This is based on PHP 4.x code which uses a few poor practices, like ignoring variable initialization.
Here’s what you want:
************
“Mattias”, “IQ” => 250),
array(“First name” => “Tony”, “IQ” => 100),
array(“First name” => “Peter”, “IQ” => 100),
array(“First name” => “Edvard”, “IQ” => 100)
);
fwrite($fp, serialize($assoc));
fclose($fp);
header (“Content-type: application/x-msexcel”);
header (“Content-Disposition: attachment; filename=\”" . basename($export_file) . “\”" );
readfile($export_file);
header (“Expires: Mon, 26 Jul 1997 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”);
readfile(“/tmp/$filename”);
************
Also, you should remove *all* close tag (?>) endings in the files, as any extra white space can screw up the download MIME sniff.
Lastly, (most critical), you need to make these changes to excel.php:
At line 108, add:
$data = ”;
At line 142, add:
$size = 0;
Otherwise, you’ll get warnings (at least running under E_ALL).
Cheers!
p.s. Unless it’s not completely obvious, you need a /tmp directory which the apache/php owner can write too, and if you need to reuse the file, grab it quickly, because though the default in excel.php is ‘rb’ file creation, the example here and included at PHPClasses is ‘wb’ which will wipe it each time.
October 7th, 2009 at 12:56 pm
Thanks geekdad,
I think you nailed everything there!
You are complete correct that the code is PHP4 with some bad practice, and like I have said earlier I will try to complete a better and more modern tutorial about excel creating in PHP.
If you are interested in guest posting here at 999tutorials just let me know, we would be glad to have you onboard! I notice that you have some coding skills that lots of people might appreciate!
October 8th, 2009 at 7:32 pm
Thanks for the nice code. I have two questions:
How does he know what cell and column to fill in the xls file?
Do we need to stay with the file on the server, or it’s possible to do this, without saving the file on the server, or at least, not in a way where the file should stay there?
Thanks a lot,
Mem
October 8th, 2009 at 7:34 pm
Sorry for the first question, I didn’t notice you were using a class… Let’s forget about that first question.
Regards,
MEM
October 9th, 2009 at 3:42 am
Thanks guys for your help.
Cheers
October 26th, 2009 at 8:40 pm
thank for your tutorial and link
November 19th, 2009 at 5:40 am
Hey Guys,
I m getting same kind of output as “nagarjuna”
I m also using linux system
Try to figure it out if possible
Here’s what i got
a:3:{i:0;a:5:{s:12:”Sales Person”;s:11:”Sam Jackson”;s:2:”Q1″;s:5:”$3255″;s:2:”Q2″;s:5:”$3167″;s:2:”Q3″;i:3245;s:2:”Q4″;i:3943;}…
December 19th, 2009 at 10:41 pm
Hey , nice technique , but I would like to add that dont use this technique if you want your users to generate excels/any file on the fly and download.
Because if you have lots of users on this page then just imagine how much load server will take. because its contain all file handling code.
Instead of this you can use some simple headers to create excel files on the fly and set it for force download.
heres a sample of headers to create any file
// We’ll be outputting a PDF
header(‘Content-type: application/pdf’);
tells browser that coming data is not plain html but pdf
// It will be called downloaded.pdf
header(‘Content-Disposition: attachment; filename=”filename.pdf”‘);
header(“Content-Type: application/force-download”);
above lines will tell browser for force download with specified file name. so user will get dialog box of save or open.
C no file handling..
January 1st, 2010 at 11:04 pm
Are you able to give you a link but http://www.phpclasses.org, because I could not from the site registration
February 2nd, 2010 at 11:38 am
Hi,
That was a nice tutorial. But I have one question.
How do I add more data to the same excel file. For example say I am executing the file, I get 3 rows of data. Suppose I want to add the fourth one what should I do?
Thanks
Suji
February 8th, 2010 at 3:04 pm
Not sure if I understand what you try to do.
Do you want to edit an excel file that you created earlier and add more an additional row?
Unfortunately that is not possible with this method, because the class can not open and read existing files.
We will try to get a new improved excel tutorial online soon though that might help you!
February 8th, 2010 at 3:09 pm
Unfortunately not, you have to signup with phpclasses.org, but it’s free.
February 24th, 2010 at 7:09 am
hi
can you explain how to create excel file with format