Posted By

SteveMcDaniel on 10/09/09


Tagged

mysql php excel export


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

vali29
fackz


Export to MS Excel for MySQL Database


 / Published in: PHP
 

  1. <?php
  2.  
  3. # export to excel
  4.  
  5. $link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
  6. $select = "SELECT * FROM table";
  7. $export = mysql_query ( $select ) or die ( "Sql error : " . mysql_error( ) );
  8. $fields = mysql_num_fields ( $export );
  9. for ( $i = 0; $i < $fields; $i++ )
  10. {
  11. $header .= mysql_field_name( $export , $i ) . "\t";
  12. }
  13. while( $row = mysql_fetch_row( $export ) )
  14. {
  15. $line = '';
  16. foreach( $row as $value )
  17. {
  18. if ( ( !isset( $value ) ) || ( $value == "" ) )
  19. {
  20. $value = "\t";
  21. }
  22. else
  23. {
  24. $value = str_replace( '"' , '""' , $value );
  25. $value = '"' . $value . '"' . "\t";
  26. }
  27. $line .= $value;
  28. }
  29. $data .= trim( $line ) . "\n";
  30. }
  31. $data = str_replace( "\r" , "" , $data );
  32. if ( $data == "" )
  33. {
  34. $data = "\n(0) Records Found!\n";
  35. }
  36.  
  37. header("Content-type: application/octet-stream");
  38. header("Content-Disposition: attachment; filename=your_desired_name.xls");
  39. header("Pragma: no-cache");
  40. header("Expires: 0");
  41. print "$header\n$data";?>

Report this snippet  

You need to login to post a comment.