ExportService.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <?php
  2. /**
  3. *
  4. * @author: xaboy<365615158@qq.com>
  5. * @day: 2018/01/23
  6. */
  7. namespace service;
  8. class ExportService
  9. {
  10. public static function exportCsv($list,$filename,$header = [],$br = '_'){
  11. $tableStr = count($header) > 0 ? '"'.implode('","',$header).'"'.PHP_EOL : '';
  12. $tableStr .= self::tidyCsvStr($list,str_repeat($br,99));
  13. ob_end_clean();
  14. ob_start();
  15. header("Content-type:application/vnd.ms-excel");
  16. header("Content-Disposition:filename=".$filename.".csv");
  17. header('Content-Type:application/download');
  18. exit(iconv('UTF-8',"GB2312//IGNORE",$tableStr));
  19. }
  20. private static function tidyCsvStr($list,$br = '')
  21. {
  22. $tableStr = '';
  23. foreach ($list as $row){
  24. if(is_array($row)){
  25. $max = 1;
  26. foreach ($row as $k=>$item){
  27. if(is_array($item)){
  28. if($max < ($l = count($item))) $max = $l;
  29. } else
  30. $row[$k] = [$item];
  31. }
  32. for($i = 0; $i<=$max; $i++){
  33. $exportRow = [];
  34. if($max == $i){
  35. if($br == '')
  36. continue;
  37. else
  38. $exportRow = array_fill(0,count($row),$br);
  39. }else{
  40. foreach ($row as $item){
  41. $exportRow[] = isset($item[$i]) && !empty($item[$i]) ? $item[$i] : ' ';
  42. }
  43. }
  44. $tableStr .= '"'.implode('","',$exportRow).'"," "'.PHP_EOL;
  45. }
  46. $tableStr = rtrim($tableStr,PHP_EOL);
  47. }else{
  48. $tableStr .= implode('',['"',$row,'"',',']);
  49. }
  50. $tableStr .= PHP_EOL;
  51. }
  52. return $tableStr;
  53. }
  54. }