CSV导出类
use Hyperf\HttpMessage\Stream\SwooleStream;
use Hyperf\HttpServer\Response;
class ExportLogic
{
public static function export(array $head, array $body, string $file_name)
{
$head_keys = array_keys($head);
$head_values = array_values($head);
$fileData = self::utfToGbk(implode(',', $head_values)) . "\n";
if (strpos($file_name, '.') === false) {
$file_name .= '.csv';
}
foreach ($body as $value) {
$temp_arr = [];
foreach ($head_keys as $key) {
$temp_arr[] = $value[$key] ?? '';
}
$fileData .= self::utfToGbk(implode(',', $temp_arr)) . "\n";
}
$response = new Response();
$content_type = 'text/csv';
return $response->withHeader('content-description', 'File Transfer')
->withHeader('content-type', $content_type)
->withHeader('content-disposition', "attachment; filename={$file_name}")
->withHeader('content-transfer-encoding', 'binary')
->withHeader('pragma', 'public')
->withBody(new SwooleStream($fileData));
}
/**
* 字符转换(utf-8 => GBK)
* @param $data
* @return false|string
*/
public static function utfToGbk($data)
{
return mb_convert_encoding($data, "GBK", "UTF-8");
}
}
在控制器中调用
public function export()
{
$start = $this->request->input('start_day', Carbon::now()->subWeek()->startOfWeek()->toDateString());
$end = $this->request->input('end_day', Carbon::now()->subWeek()->endOfWeek()->toDateString());
$list = $this->getDepartmentRank($start, $end);
$fileName = '部门排行榜' . $start . '-' . $end;
return ExportLogic::export([
"rank" => '排名',
"department_name" => '归属部门',
"total_score" => '质检得分',
"level" => '评价等级',
], $list, $fileName);
}