1. 程式人生 > 其它 >TP5匯出scv格式資料

TP5匯出scv格式資料

/**
* 匯出CSV格式
* @param $headArr 匯出內容表頭
* @param $exportData 匯出資料內容
* @param $title 匯出的標題
* @createTime:2021-6-22 11:50
* @author:LTTT
*/
public function exportCsv($headArr, $exportData, $title = '')
{
if (empty($headArr) || empty($exportData)) {
throw new \Exception("表頭或者內容不能為空");
}
if (empty($title)) {
     // 標題根據自己需要生成
$title = time();
}
$total = count($exportData);
header("Content-type:application/vnd.ms-excel");
header("Content-Disposition:filename=" . iconv("UTF-8", "GB18030", $title) . ".csv");
$fp = fopen('php://output', 'a');
$headName = array_keys($headArr);
$headValue = array_values($headArr);
fputcsv($fp, $headValue);
$size = 2000;
$groupNum = ceil($total / $size);
for ($i = 0; $i <= $groupNum; $i++) {
$exportDataTemp = array_slice($exportData, $size * $i, $size);
foreach ($exportDataTemp as $item) {
$rows = array();
foreach ($headName as $name) {
$rows[] = $item[$name];
}
fputcsv($fp, $rows);
}
ob_flush();
flush();
}
die;
}