PHP 实时生成并下载超大数据量的 Excel 文件
//另外由于excel数据是从数据库里逐步读出然后写入输出流的所以需要将PHP的执行时间设长一点
//(默认30秒)set_time_limit(0)不对PHP执行时间做限制。
set_time_limit(0);
$columns = [
'文章ID', '文章标题', ...... //'openid'
];
//处理需要导出的数据
$timeStart = strtotime('2018-08-08 00:00:00');
$timeEnd = strtotime('2018-08-08 23:59:59');
$arr = DB::table('t_wechat_user_wx4ed9e1f4e0f3eeb0')->select(DB::raw('distinct openid'))->where('subscribe_time','>=',$timeStart)->where('subscribe_time','<=',$timeEnd);
$csvFileName = '8月8号新增粉丝openid.xlsx';
//设置好告诉浏览器要下载excel文件的headers
header('Content-Description: File Transfer');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename="'. $csvFileName .'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
$fp = fopen('php://output', 'a');//打开output流
mb_convert_variables('GBK', 'UTF-8', $columns);
fputcsv($fp, $columns);//将数据格式化为CSV格式并写入到output流中
$accessNum = $arr->count();//从数据库获取总量,假设是一百万
$perSize = 1000;//每次查询的条数
$pages = ceil($accessNum / $perSize);
$lastId = 0;
for($i = 1; $i <= $pages; $i++) {
//需要导出的数据
$accessLog = $arr->offset($lastId)->limit($perSize)->get(['openid'])->toArray();
foreach($accessLog as $access) {
$rowData = [
......//每一行的数据 $access->openid
];
mb_convert_variables('GBK', 'UTF-8', $rowData);
fputcsv($fp, $rowData);
$lastId ++;
}
unset($accessLog);//释放变量的内存
//刷新输出缓冲到浏览器
ob_flush();
flush();//必须同时使用 ob_flush() 和flush() 函数来刷新输出缓冲。
}
fclose($fp);
exit();
本作品采用《CC 协议》,转载必须注明作者和本文链接
本帖由系统于 4年前 自动加精
这就是
csv
为什么还有指定拓展名为xlsx
记得有个 chunk 查询 了解一下..
id如果不连续有问题吧
这个是导出csv的吧?能直接导出xlsx?
推荐一个功能丰富、兼容性好、高性能的 Excel 文档基础库:github.com/xuri/excelize