ExportService.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2020 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. namespace service;
  12. class ExportService
  13. {
  14. public static function exportCsv($list,$filename,$header = [],$br = '_'){
  15. $tableStr = count($header) > 0 ? '"'.implode('","',$header).'"'.PHP_EOL : '';
  16. $tableStr .= self::tidyCsvStr($list,str_repeat($br,99));
  17. ob_end_clean();
  18. ob_start();
  19. header("Content-type:application/vnd.ms-excel");
  20. header("Content-Disposition:filename=".$filename.".csv");
  21. header('Content-Type:application/download');
  22. exit(iconv('UTF-8',"GB2312//IGNORE",$tableStr));
  23. }
  24. private static function tidyCsvStr($list,$br = '')
  25. {
  26. $tableStr = '';
  27. foreach ($list as $row){
  28. if(is_array($row)){
  29. $max = 1;
  30. foreach ($row as $k=>$item){
  31. if(is_array($item)){
  32. if($max < ($l = count($item))) $max = $l;
  33. } else
  34. $row[$k] = [$item];
  35. }
  36. for($i = 0; $i<=$max; $i++){
  37. $exportRow = [];
  38. if($max == $i){
  39. if($br == '')
  40. continue;
  41. else
  42. $exportRow = array_fill(0,count($row),$br);
  43. }else{
  44. foreach ($row as $item){
  45. $exportRow[] = isset($item[$i]) && !empty($item[$i]) ? $item[$i] : ' ';
  46. }
  47. }
  48. $tableStr .= '"'.implode('","',$exportRow).'"," "'.PHP_EOL;
  49. }
  50. $tableStr = rtrim($tableStr,PHP_EOL);
  51. }else{
  52. $tableStr .= implode('',['"',$row,'"',',']);
  53. }
  54. $tableStr .= PHP_EOL;
  55. }
  56. return $tableStr;
  57. }
  58. }