HTML Table to Excel File Tutorial

Filed Under (General) by Wenbert on 02-10-2007

Tagged Under : ,

Here is a tutorial on how to export something from your database to an excel file using PHP. It is useful when you want to download a report.

Basically, it displays an HTML table but instead of showing it in the browser, we have set the header to treat the output as an excel file.

  1. $dbhost = ‘localhost’;
  2. $dbuser = ‘root’;
  3. $dbpass = ‘xxx’;
  4.  
  5. $conn = mysql_connect($dbhost, $dbuser, $dbpass) or die (‘Error connecting to mysql’);
  6.  
  7. $dbname = ‘employee’;
  8. mysql_select_db($dbname);
  9.  
  10. $query  = ‘SELECT
  11.            *
  12.            FROM employee_table’;
  13.  
  14. $result = mysql_query($query);
  15.  
  16. header("Pragma: public");
  17. header("Cache-Control: no-store, no-cache, must-revalidate");
  18. header("Cache-Control: pre-check=0, post-check=0, max-age=0");
  19. header("Pragma: no-cache");
  20. header("Expires: 0");
  21. header("Content-Transfer-Encoding: none");
  22. header("Content-Type: application/vnd.ms-excel;");
  23. header("Content-type: application/x-msexcel");
  24. header("Content-Disposition: attachment; filename=my_excel_file.xls");
  25.  
  26. echo
  27. <table border="1">’;
  28. echo
  29. <tbody>
  30. <tr>’;
  31. echo
  32. <td><strong>Firt Name</strong></td>
  33. ;
  34. echo
  35. <td><strong>Last Name</strong></td>
  36. ;
  37. echo
  38. <td><strong>Username</strong></td>
  39. ;
  40. echo
  41. <td><strong>Date Hired</strong></td>
  42. ;
  43. echo
  44. <td><strong>Marital Status</strong></td>
  45. ;
  46.  
  47. while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
  48.     echo ‘</tr>
  49. <tr>’;
  50.     echo
  51. <td>’.$row[‘firstname’].‘</td>
  52. ;
  53.     echo
  54. <td>’.$row[‘lastname’].‘</td>
  55. ;
  56.     echo
  57. <td>’.$row[‘username’].‘</td>
  58. ;
  59.     echo
  60. <td>’.$row[‘datehired’].‘</td>
  61. ;
  62.     echo
  63. <td>’.$row[‘maritalstatus’].‘</td>
  64. ;
  65.     echo ‘</tr>
  66. ;
  67. }
  68.  
  69. echo ‘</tbody></table>
  70. ;

Leave a Reply