Posted By

tclancy on 02/23/09


Tagged


Versions (?)

Who likes this?

6 people have marked this snippet as a favorite

jfherring
brent-man
umang_nine
Anber
vali29
BrianCoyDesign


Excel Exporter


 / Published in: PHP
 

URL: http://www.thosecleverkids.com/blog/2009/02/23/php-excel-exporter/

  1. require_once("data-class.php");
  2.  
  3. class ExcelExporter
  4. {
  5. var $column_heads = array();
  6. var $date_format = "m/d/y";
  7. var $debug = false;
  8. var $filename = "export.xls";
  9. var $timestamp_file = false;
  10.  
  11. var $_conn = false;
  12.  
  13. function ExcelExporter()
  14. {
  15. $this->_conn = new DataConnection();
  16. }
  17.  
  18. function set_filename($name)
  19. {
  20. $this->_filename = $name;
  21. }
  22.  
  23. function export($sql)
  24. {
  25. $this->_conn->query($sql);
  26.  
  27. if (!$this->debug)
  28. {
  29. $this->_serve_excel_headers();
  30. }
  31.  
  32. if ($this->_conn->getNumberOfRows() == 0)
  33. {
  34. return $this->_get_table(false);
  35. }
  36. return $this->_get_table($this->_conn->getResultSet());
  37. }
  38.  
  39. /* INTERNALS */
  40. function _get_table($results)
  41. {
  42. $table = "<table border=\"1\">\n";
  43. $table .= $this->_get_header_row();
  44. if ($results)
  45. {
  46. foreach($results as $info)
  47. {
  48. $table .= "\n<tr>";
  49. foreach($info as $k => $v)
  50. {
  51. $table .= sprintf("\n\t<td>%s</td>", $this->_format_field($k, $v));
  52. }
  53. $table .= "\n</tr>";
  54. }
  55. }
  56.  
  57. $table .= "\n</table>";
  58.  
  59. return $table;
  60. }
  61.  
  62. function _get_header_row()
  63. {
  64. $output = "\n<tr>";
  65. foreach ($this->column_heads as $header)
  66. {
  67. $output .= sprintf("\n\t<th>%s</th>", $header);
  68. }
  69. $output .= "\n</tr>";
  70. return $output;
  71. }
  72.  
  73. function _format_field($name, $value)
  74. {
  75. if (false == stristr($name, "_date"))
  76. {
  77. return $value;
  78. }
  79.  
  80. return date($this->date_format, $value);
  81. }
  82.  
  83. function _serve_excel_headers()
  84. {
  85. header ("Content-type: application/x-msexcel");
  86. header ("Content-Disposition: attachment; filename=\"" . $this->_get_filename() . "\"" );
  87. }
  88.  
  89. function _get_filename()
  90. {
  91. $name = $this->filename;
  92. if (!$this->timestamp_file)
  93. {
  94. return $name;
  95. }
  96. $now = "-".time();
  97. $pieces = split("\.", $name);
  98. $stamped_name = $pieces[0].$now;
  99. if (count($pieces) == 2)
  100. {
  101. $stamped_name .= ".".$pieces[1];
  102. }
  103. return $stamped_name;
  104. }
  105. }

Report this snippet  

You need to login to post a comment.