reenadak

Script for downloading MySql table in Excel

Sep 25th, 2017
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.00 KB | None | 0 0
  1. <?php
  2. ob_start();
  3.  
  4. // Script for downloading MySql table in Excel
  5.  
  6. /**
  7. * @author sapta
  8. * @copyright 2009
  9. */
  10.  
  11. $cdate = date("Y-m-d"); // get current date
  12.  
  13. // configuration
  14. $mysql_host = '';
  15. $mysql_user = '';
  16. $mysql_pass = '';
  17. $mysql_db = '';
  18. $query_string = "select * from sdm";
  19. $export_filename = "exported_table_on_$cdate.xls";
  20.  
  21.  
  22. // connect to mysql server
  23. $mysql_link = mysql_connect($mysql_host,$mysql_user,$mysql_pass);
  24. mysql_select_db($mysql_db,$mysql_link);
  25.  
  26. // query from table
  27. $result = mysql_query($query_string);
  28.  
  29. $count = mysql_num_fields($result);
  30.  
  31. // fetch table header
  32. $header = '';
  33. for ($i = 0; $i < $count; $i++){
  34. $header .= mysql_field_name($result, $i)."\t";
  35. }
  36.  
  37. // fetch data each row, store on tabular row data
  38. while($row = mysql_fetch_row($result)){
  39. $line = '';
  40. foreach($row as $value){
  41. if(!isset($value) || $value == ""){
  42. $value = "\t";
  43. }else{
  44. # important to escape any quotes to preserve them in the data.
  45. $value = str_replace('"', '""', $value);
  46. # needed to encapsulate data in quotes because some data might be multi line.
  47. # the good news is that numbers remain numbers in Excel even though quoted.
  48. $value = '"' . $value . '"' . "\t";
  49. }
  50.  
  51. $line .= $value;
  52. }
  53. $data .= trim($line)."\n";
  54. }
  55.  
  56. # this line is needed because returns embedded in the data have "\r"
  57. # and this looks like a "box character" in Excel
  58. $data = str_replace("\r", "", $data);
  59.  
  60. # Nice to let someone know that the search came up empty.
  61. # Otherwise only the column name headers will be output to Excel.
  62. if ($data == "") {
  63. $data = "\nno matching records found\n";
  64. }
  65.  
  66. // create table header showing to download a xls (excel) file
  67. header("Content-type: application/octet-stream");
  68. header("Content-Disposition: attachment; filename=$export_filename");
  69. header("Cache-Control: public");
  70. header("Content-length: ".strlen($data)); // tells file size
  71. header("Pragma: no-cache");
  72. header("Expires: 0");
  73.  
  74. // output data
  75. // echo $header."\n".$data;
  76. echo $data;
  77.  
  78. ?>
Add Comment
Please, Sign In to add comment