1.导出函数
/**
* 导出csv
* @param array $data 导出的数据
* @param array $headList 头部文字描述
* @param string $fileName 文件名
*/
function csvExport($data, $headList, $fileName)
{
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="' . $fileName . '.csv"');
header('Cache-Control: max-age=0');
$fp = fopen('php://output', 'a');
foreach ($headList as $key => $value) {
$headList[$key] = iconv('utf-8', 'gbk', $value);
}
fputcsv($fp, $headList);
$num = 0;
$limit = 100000;
$count = count($data);
for ($i = 0; $i < $count; $i++) {
$num++;
if ($limit == $num) {
ob_flush();
flush();
$num = 0;
}
$row = $data[$i];
foreach ($row as $key => $value) {
$row[$key] = iconv('utf-8', 'gbk', $value);
}
fputcsv($fp, $row);
}
}
2.导出操作
/**
* 导出数据
* @hrows \Exception
*/
public function actionExport()
{
//获取用户数据
$data = User::find()->asArray()->all();
$num = 0;
foreach ($data as $value) {
// 序号
$dataInfo[$num][] = $num + 1;
// 日期
$dataInfo[$num][] = date("Y年m月", strtotime($value['login_time']));
// 用户名
$dataInfo[$num][] = $value['user_name'];
$num++;
}
$headList = [
'序号',
'日期',
'用户名'
];
$title = "导出cvs数据";
//调用上面的方法
csvExport($dataInfo, $headList, $title);
}