Rumah  >  Artikel  >  pembangunan bahagian belakang  >  php 导出数据到excel类

php 导出数据到excel类

WBOY
WBOYasal
2016-07-25 08:50:551009semak imbas
将数据导出到excel当中,欢迎大家拍砖
  1. /**
  2. * 导出到excel文件(一般导出中文的都会乱码,需要进行编码转换)
  3. * 使用方法如下
  4. * $excel = new Excel();
  5. * $excel->addHeader(array('列1','列2','列3','列4'));
  6. * $excel->addBody(
  7. array(
  8. array('数据1','数据2','数据3','数据4'),
  9. array('数据1','数据2','数据3','数据4'),
  10. array('数据1','数据2','数据3','数据4'),
  11. array('数据1','数据2','数据3','数据4')
  12. )
  13. );
  14. * $excel->downLoad();
  15. */
  16. class Excel{
  17. private $head;
  18. private $body;
  19. /**
  20. *
  21. * @param type $arr 一维数组
  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 二维数组
  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. * 下载excel文件
  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. * 编码转换
  58. * @param type $string
  59. * @return string
  60. */
  61. public function charset($string){
  62. return iconv("utf-8", "gb2312", $string);
  63. }
  64. }
  65. ?>
复制代码


Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn