You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
zhishifufei_php/extend/service/ExportService.php

65 lines
2.5 KiB

10 months ago
<?php
// +----------------------------------------------------------------------
// | 天诚科技 [ 刘海东 17600099397赋能开发者,助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2020 https://www.tczxkj.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 该系统并不是自由软件,未经许可不能去掉相关版权
// +----------------------------------------------------------------------
// | Author:甘肃天诚志信电子商务有限公司 刘海东 联系电话维系17600099397
// +----------------------------------------------------------------------
namespace service;
class ExportService
{
public static function exportCsv($list, $filename, $header = [], $br = '_')
{
$tableStr = count($header) > 0 ? '"' . implode('","', $header) . '"' . PHP_EOL : '';
$tableStr .= self::tidyCsvStr($list, str_repeat($br, 99));
ob_end_clean();
ob_start();
header("Content-type:application/vnd.ms-excel");
header("Content-Disposition:filename=" . $filename . ".csv");
header('Content-Type:application/download');
exit(iconv('UTF-8', "GB2312//IGNORE", $tableStr));
}
private static function tidyCsvStr($list, $br = '')
{
$tableStr = '';
foreach ($list as $row) {
if (is_array($row)) {
$max = 1;
foreach ($row as $k => $item) {
if (is_array($item)) {
if ($max < ($l = count($item))) $max = $l;
} else
$row[$k] = [$item];
}
for ($i = 0; $i <= $max; $i++) {
$exportRow = [];
if ($max == $i) {
if ($br == '')
continue;
else
$exportRow = array_fill(0, count($row), $br);
} else {
foreach ($row as $item) {
$exportRow[] = isset($item[$i]) && !empty($item[$i]) ? $item[$i] : ' ';
}
}
$tableStr .= '"' . implode('","', $exportRow) . '"," "' . PHP_EOL;
}
$tableStr = rtrim($tableStr, PHP_EOL);
} else {
$tableStr .= implode('', ['"', $row, '"', ',']);
}
$tableStr .= PHP_EOL;
}
return $tableStr;
}
}