Posted By

brownrl on 06/26/09


php excel xls

Versions (?)

Who likes this?

10 people have marked this snippet as a favorite


PHP Export MySql Table to Xls

 / Published in: PHP


Face it!

Whenever you make a website/app you always need to make XLS export for the simple people. I mean heaven to betsy if they have to take a csv file, or use phpMyAdmin.


Here are 3 little functions and a sample skeleton that I use from time to time when I need to export out some data to an xls file.

Place the file in a safe place or if you want a completely open to the world place... :D Then replace the XXXXX's with the appropriate data.

Give the pointy haired boss the links!

  1. <?php
  3. // DB TABLE Exporter
  4. //
  5. // How to use:
  6. //
  7. // Place this file in a safe place, edit the info just below here
  8. // browse to the file, enjoy!
  12. $dbhost = "";
  13. $dbuser = "XXXXX";
  14. $dbpass = "XXXXX";
  15. $dbname = "XXXXX";
  16. $dbtable = "XXXXX";
  21. // first thing that we are going to do is make some functions for writing out
  22. // and excel file. These functions do some hex writing and to be honest I got
  23. // them from some where else but hey it works so I am not going to question it
  24. // just reuse
  27. // This one makes the beginning of the xls file
  28. function xlsBOF() {
  29. echo pack("ssssss", 0x809, 0x8, 0x0, 0x10, 0x0, 0x0);
  30. return;
  31. }
  33. // This one makes the end of the xls file
  34. function xlsEOF() {
  35. echo pack("ss", 0x0A, 0x00);
  36. return;
  37. }
  39. // this will write text in the cell you specify
  40. function xlsWriteLabel($Row, $Col, $Value ) {
  41. $L = strlen($Value);
  42. echo pack("ssssss", 0x204, 8 + $L, $Row, $Col, 0x0, $L);
  43. echo $Value;
  44. return;
  45. }
  49. // make the connection an DB query
  50. $dbc = mysql_connect( $dbhost , $dbuser , $dbpass ) or die( mysql_error() );
  51. mysql_select_db( $dbname );
  52. $q = "SELECT * FROM ".$dbtable."";
  53. $qr = mysql_query( $q ) or die( mysql_error() );
  56. // Ok now we are going to send some headers so that this
  57. // thing that we are going make comes out of browser
  58. // as an xls file.
  59. //
  60. header("Pragma: public");
  61. header("Expires: 0");
  62. header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
  63. header("Content-Type: application/force-download");
  64. header("Content-Type: application/octet-stream");
  65. header("Content-Type: application/download");
  67. //this line is important its makes the file name
  68. header("Content-Disposition: attachment;filename=export_".$dbtable.".xls ");
  70. header("Content-Transfer-Encoding: binary ");
  72. // start the file
  73. xlsBOF();
  75. // these will be used for keeping things in order.
  76. $col = 0;
  77. $row = 0;
  79. // This tells us that we are on the first row
  80. $first = true;
  82. while( $qrow = mysql_fetch_assoc( $qr ) )
  83. {
  84. // Ok we are on the first row
  85. // lets make some headers of sorts
  86. if( $first )
  87. {
  88. foreach( $qrow as $k => $v )
  89. {
  90. // take the key and make label
  91. // make it uppper case and replace _ with ' '
  92. xlsWriteLabel( $row, $col, strtoupper( ereg_replace( "_" , " " , $k ) ) );
  93. $col++;
  94. }
  96. // prepare for the first real data row
  97. $col = 0;
  98. $row++;
  99. $first = false;
  100. }
  102. // go through the data
  103. foreach( $qrow as $k => $v )
  104. {
  105. // write it out
  106. xlsWriteLabel( $row, $col, $v );
  107. $col++;
  108. }
  109. // reset col and goto next row
  110. $col = 0;
  111. $row++;
  112. }
  114. xlsEOF();
  115. exit();
  116. ?>

Report this snippet  


RSS Icon Subscribe to comments
Posted By: shana on October 1, 2009

Thank u for the code....But how can we increase the column width of the xls file

Posted By: brownrl on October 5, 2009

You don't the Excel has a default size. The best thing to do is select all Ctrl-A then double click the edge of the first column and all columns will spread out to the size that is needed. This code here makes the absolute most basic excel file possible. There might be some other php libs out to do more fancy stuff.

Posted By: mdemetri2 on November 26, 2009

Hi, just tried to implement this - I am getting a load of "Warning: Cannot modify header information - headers already sent by (output started at /path/testdl.php:6) in /home/sites/ on line 77" through to line 87. When you open up the page testdl.php its not opening as an excel file just test in the browser.

Posted By: mdemetri2 on November 26, 2009

Hi, just tried to implement this - I am getting a load of "Warning: Cannot modify header information - headers already sent by (output started at /path/testdl.php:6) in /home/sites/ on line 77" through to line 87. When you open up the page testdl.php its not opening as an excel file just test in the browser.

Posted By: brownrl on November 27, 2009


What is happening according to your error is that on line 6 of your php you are outputting something... in my file line 6 is a comment...

So when you get down to the part where the php is constructing and xls file and not an text/html file the web server is saying:

"Yo jerk! your already started outputting text/html we can start output binary/xls"

Check you line 6, post your code?

Posted By: bell418 on May 19, 2010

Thanks a lot for this works fine :) I messed around for a while with more 'complex' codes, with no acceptable result.

good work!

Posted By: brownrl on September 17, 2010

I use this base script numerous times. Normally I add a quick "if" there to convert "date" and "timestamp" fields from integers to human readable dates. I also have used this in combination with another html form to make a universal db exporter.

This here is simply the base.

Posted By: mateinone on April 1, 2011

Thanks, Sorry this is probably a simple error, but it is not writing to a file, it is writing to my webpage in a manner as follows �� ��� �1210049297 This is something that would be a great asset to me if I could get it to work

Posted By: mateinone on April 1, 2011

Sorry about the multiple posts, I refreshed the page and each time I just noticed it was posting the same details again

Posted By: brownrl on April 8, 2011

thats odd.

check to make absolutely sure that you are not already starting output some where else in your program. A blank line of html will tell apache that this is now text and no longer allow the binary header stuff to go.

You output looks like binary stuff, so really I believe that you are already outputting to the screen somewhere and you have error reporting turned off. Otherwise you would see an error like above: Warning: Cannot modify header information - headers already sent by

Posted By: srosca on May 21, 2011

How can I save the file to the server and not the users computer?

Posted By: brownrl on June 27, 2011

probably by outputing the data to file instead of out to the screen? So instead of "echo" add the data to a temp string, then write the big temp string to a file. fileputcontents( $temp , $somefile ).

Posted By: mdemetri2 on March 30, 2012

Hi, been using this code for a while, but have now noticed that it is limited to 255 characters in each cell. Any db table field that holds any more than 255 characters it just doesnt export that field into a cell in there a way to increase the limit?

Posted By: brownrl on March 30, 2012

talks about the char max. Never needed to have more than 255 chars in a cell. Take a look.

You need to login to post a comment.