public function export(Request $request)
{
  // 查询数据库数据
  $list = .....;
  $this->userListExport($list);
}

public function userListExport($list)
{
// 导出充值记录的头部信息
$cell = ['头像', '微信昵称', '备注', ];

$cellData = [];
foreach ($list as &$value) {
       // 填充数据
$cellData[] = ([
'',
'',
'',
]);
}
$this->exportUser($cell, $cellData);
}


public function exportUser($cell, $data, $title = '客户列表')
{
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="' . $title . '.csv"');
header('Cache-Control: max-age=0');

set_time_limit(0); // 设置脚本最大执行时间 为0
ini_set('memory_limit', '1024M'); // 临时设置最大内存占用

// 打开PHP文件句柄,php://output 表示直接输出到浏览器
$fp = fopen('php://output', 'a');

$column_name = [];
// 将中文标题转换编码,否则乱码
foreach ($cell as $i => $v) {
$column_name[$i] = iconv('utf-8', 'GBK//IGNORE', $v);
}

// 将标题名称通过fputcsv写到文件句柄
fputcsv($fp, $column_name);
foreach ($data as $row) {
foreach ($row as $key => $item) {
$row[$key] = iconv('utf-8', 'GBK//IGNORE', $item);
}
fputcsv($fp, $row);
}
$res = ['file' => $title];
return response()->json($res);
}
posted on 2021-12-10 14:06  able-woman  阅读(501)  评论(0编辑  收藏  举报