Hyperf导出csv

CSV导出类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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 falsestring
*/
public static function utfToGbk($data)
{
return mb_convert_encoding($data, "GBK", "UTF-8");
}
}

在控制器中调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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);
}

Hyperf导出csv
https://lejtao.online/2022/05/08/hyperf导出csv/
作者
LeJTao
发布于
2022年5月9日
许可协议