ExportService.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2022 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. {
  16. $tableStr = count($header) > 0 ? '"' . implode('","', $header) . '"' . PHP_EOL : '';
  17. $tableStr .= self::tidyCsvStr($list, str_repeat($br, 99));
  18. ob_end_clean();
  19. ob_start();
  20. header("Content-type:application/vnd.ms-excel");
  21. header("Content-Disposition:filename=" . $filename . ".csv");
  22. header('Content-Type:application/download');
  23. exit(iconv('UTF-8', "GB2312//IGNORE", $tableStr));
  24. }
  25. private static function tidyCsvStr($list, $br = '')
  26. {
  27. $tableStr = '';
  28. foreach ($list as $row) {
  29. if (is_array($row)) {
  30. $max = 1;
  31. foreach ($row as $k => $item) {
  32. if (is_array($item)) {
  33. if ($max < ($l = count($item))) $max = $l;
  34. } else
  35. $row[$k] = [$item];
  36. }
  37. for ($i = 0; $i <= $max; $i++) {
  38. $exportRow = [];
  39. if ($max == $i) {
  40. if ($br == '')
  41. continue;
  42. else
  43. $exportRow = array_fill(0, count($row), $br);
  44. } else {
  45. foreach ($row as $item) {
  46. $exportRow[] = isset($item[$i]) && !empty($item[$i]) ? $item[$i] : ' ';
  47. }
  48. }
  49. $tableStr .= '"' . implode('","', $exportRow) . '"," "' . PHP_EOL;
  50. }
  51. $tableStr = rtrim($tableStr, PHP_EOL);
  52. } else {
  53. $tableStr .= implode('', ['"', $row, '"', ',']);
  54. }
  55. $tableStr .= PHP_EOL;
  56. }
  57. return $tableStr;
  58. }
  59. }