Excel.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. /**
  3. * 生成excel文件操作
  4. *
  5. * @author wesley wu
  6. * @date 2013.12.9
  7. */
  8. class Excel
  9. {
  10. private $limit = 10000;
  11. public function download($data, $fileName, $width_data = array())
  12. {
  13. $fileName = $this->_charset($fileName);
  14. header("Content-Type: application/vnd.ms-excel; charset=gbk");
  15. header("Content-Disposition: inline; filename=\"" . $fileName . ".xls\"");
  16. echo "<?xml version=\"1.0\" encoding=\"gbk\"?>\n
  17. <Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"
  18. xmlns:x=\"urn:schemas-microsoft-com:office:excel\"
  19. xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\"
  20. xmlns:html=\"http://www.w3.org/TR/REC-html40\">";
  21. echo "\n<Worksheet ss:Name=\"" . $fileName . "\">\n<Table>\n";
  22. $Column = 0;
  23. foreach($width_data as $v){
  24. $Column++;
  25. if(empty($v)){
  26. continue;
  27. }
  28. echo "<Column ss:Index=\"".$Column."\" ss:Width=\"".floatval($v)."\" />\n";
  29. }
  30. $guard = 0;
  31. foreach($data as $v)
  32. {
  33. $guard++;
  34. if($guard==$this->limit)
  35. {
  36. ob_flush();
  37. flush();
  38. $guard = 0;
  39. }
  40. echo $this->_addRow($this->_charset($v));
  41. }
  42. echo "</Table>\n</Worksheet>\n</Workbook>";
  43. }
  44. private function _addRow($row)
  45. {
  46. $cells = "";
  47. foreach ($row as $k => $v)
  48. {
  49. $cells .= "<Cell><Data ss:Type=\"String\">" . $v . "</Data></Cell>\n";
  50. }
  51. return "<Row>\n" . $cells . "</Row>\n";
  52. }
  53. private function _charset($data)
  54. {
  55. if(!$data)
  56. {
  57. return false;
  58. }
  59. if(is_array($data))
  60. {
  61. foreach($data as $k=>$v)
  62. {
  63. $data[$k] = $this->_charset($v);
  64. }
  65. return $data;
  66. }
  67. return iconv('utf-8', 'gbk', $data);
  68. }
  69. }