Posted By

brownrl on 06/26/09


Tagged

php excel xls


Versions (?)

Who likes this?

10 people have marked this snippet as a favorite

jseltzer
vali29
calvingilbert
jcroom
joethermal
esritter
dimispaceman
beneberle
jay3917
ringo380


PHP Export MySql Table to Xls


 / Published in: PHP
 

URL: http://www.goingson.be

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.

So

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
  2.  
  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!
  9.  
  10. // CHANGE THIS STUFF FOR WHAT YOU NEED TO DO
  11.  
  12. $dbhost = "127.0.0.1:3306";
  13. $dbuser = "XXXXX";
  14. $dbpass = "XXXXX";
  15. $dbname = "XXXXX";
  16. $dbtable = "XXXXX";
  17.  
  18. // END CHANGING STUFF
  19.  
  20.  
  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
  25.  
  26.  
  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. }
  32.  
  33. // This one makes the end of the xls file
  34. function xlsEOF() {
  35. echo pack("ss", 0x0A, 0x00);
  36. return;
  37. }
  38.  
  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. }
  46.  
  47.  
  48.  
  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() );
  54.  
  55.  
  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");
  66.  
  67. //this line is important its makes the file name
  68. header("Content-Disposition: attachment;filename=export_".$dbtable.".xls ");
  69.  
  70. header("Content-Transfer-Encoding: binary ");
  71.  
  72. // start the file
  73. xlsBOF();
  74.  
  75. // these will be used for keeping things in order.
  76. $col = 0;
  77. $row = 0;
  78.  
  79. // This tells us that we are on the first row
  80. $first = true;
  81.  
  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. }
  95.  
  96. // prepare for the first real data row
  97. $col = 0;
  98. $row++;
  99. $first = false;
  100. }
  101.  
  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. }
  113.  
  114. xlsEOF();
  115. exit();
  116. ?>

Report this snippet  

Comments

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/atkinsintelligence.com/public_html/RBS/testdl.php 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/atkinsintelligence.com/public_html/RBS/testdl.php 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

hmmmm

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 code....it 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 Excel.....is there a way to increase the limit?

Posted By: brownrl on March 30, 2012

http://stackoverflow.com/questions/7044790/problem-downloading-data-to-excel-using-php-pack-function

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.