php export data to excel class

WBOY
Release: 2016-07-25 08:50:55
Original
1064 people have browsed it
将数据导出到excel当中,欢迎大家拍砖
  1. /**
  2. * Export to excel file (generally exporting Chinese will be garbled and requires encoding conversion)
  3. * The usage method is as follows
  4. * $excel = new Excel();
  5. * $excel->addHeader(array('Column 1', 'Column 2','Column 3','Column 4'));
  6. * $excel->addBody(
  7. array(
  8. array('Data 1','Data 2','Data 3','Data 4 '),
  9. array('data1','data2','data3','data4'),
  10. array('data1','data2','data3','data4') ,
  11. array('data1','data2','data3','data4')
  12. )
  13. );
  14. * $excel->downLoad();
  15. */
  16. class Excel{
  17. private $head;
  18. private $body;
  19. /**
  20. *
  21. * @param type $arr one-dimensional array
  22. */
  23. public function addHeader($arr){
  24. foreach($arr as $headVal){
  25. $headVal = $this->charset($headVal);
  26. $this->head .= "{$headVal}t ";
  27. }
  28. $this->head .= "n";
  29. }
  30. /**
  31. *
  32. * @param type $arr two-dimensional array
  33. */
  34. public function addBody($arr){
  35. foreach($arr as $arrBody){
  36. foreach($arrBody as $bodyVal){
  37. $bodyVal = $this->charset($bodyVal);
  38. $this->body .= "{$bodyVal}t ";
  39. }
  40. $this->body .= "n";
  41. }
  42. }
  43. /**
  44. * Download excel file
  45. */
  46. public function downLoad($filename=''){
  47. if(!$filename)
  48. $filename = date('YmdHis',time()).'.xls';
  49. header("Content-type:application/vnd.ms-excel");
  50. header("Content-Disposition:attachment;filename=$filename");
  51. header("Content-Type:charset=gb2312");
  52. if($this->head)
  53. echo $this->head;
  54. echo $this->body;
  55. }
  56. /**
  57. * Encoding conversion
  58. * @param type $string
  59. * @return string
  60. */
  61. public function charset($string){
  62. return iconv("utf-8", "gb2312", $string);
  63. }
  64. }
  65. ?>
复制代码


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template