php-excel.class.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. <?php
  2. class Excel_XML
  3. {
  4. /**
  5. * Header (of document)
  6. * @var string
  7. */
  8. private $header = '<?xml version="1.0" encoding="%s"?\\>
  9. <Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" xmlns:html="http://www.w3.org/TR/REC-html40">';
  10. /**
  11. * Footer (of document)
  12. * @var string
  13. */
  14. private $footer = '</Workbook>';
  15. /**
  16. * Lines to output in the excel document
  17. * @var array
  18. */
  19. private $lines = array();
  20. /**
  21. * Used encoding
  22. * @var string
  23. */
  24. private $sEncoding;
  25. /**
  26. * Convert variable types
  27. * @var boolean
  28. */
  29. private $bConvertTypes;
  30. /**
  31. * Worksheet title
  32. * @var string
  33. */
  34. private $sWorksheetTitle;
  35. public function __construct($sEncoding = 'UTF-8', $bConvertTypes = false, $sWorksheetTitle = 'Table1')
  36. {
  37. $this->bConvertTypes = $bConvertTypes;
  38. $this->setEncoding($sEncoding);
  39. $this->setWorksheetTitle($sWorksheetTitle);
  40. }
  41. public function setEncoding($sEncoding)
  42. {
  43. $this->sEncoding = $sEncoding;
  44. }
  45. public function setWorksheetTitle($title)
  46. {
  47. $title = preg_replace('/[\\\\|:|\\/|\\?|\\*|\\[|\\]]/', '', $title);
  48. $title = substr($title, 0, 31);
  49. $this->sWorksheetTitle = $title;
  50. }
  51. private function addRow($array)
  52. {
  53. $cells = '';
  54. foreach ($array as $k => $v) {
  55. $type = 'String';
  56. if ($this->bConvertTypes === true && is_numeric($v)) {
  57. $type = 'Number';
  58. }
  59. $v = htmlentities($v, ENT_COMPAT, $this->sEncoding);
  60. $cells .= '<Cell><Data ss:Type="' . $type . '">' . $v . '</Data></Cell>
  61. ';
  62. }
  63. $this->lines[] = '<Row>
  64. ' . $cells . '</Row>
  65. ';
  66. }
  67. public function addArray($array)
  68. {
  69. foreach ($array as $k => $v) {
  70. $this->addRow($v);
  71. }
  72. }
  73. public function generateXML($filename = 'excel-export')
  74. {
  75. $filename = preg_replace('/[^aA-zZ0-9\\_\\-]/', '', $filename);
  76. header('Content-Type: application/vnd.ms-excel; charset=' . $this->sEncoding);
  77. header('Content-Disposition: inline; filename="' . $filename . '.xls"');
  78. echo stripslashes(sprintf($this->header, $this->sEncoding));
  79. echo '
  80. <Worksheet ss:Name="' . $this->sWorksheetTitle . '">
  81. <Table>
  82. ';
  83. foreach ($this->lines as $line) {
  84. echo $line;
  85. }
  86. echo '</Table>
  87. </Worksheet>
  88. ';
  89. echo $this->footer;
  90. }
  91. }
  92. ?>