PHP 匯出cvs檔案
方法一:
/** * 匯出excel(csv) * @data 匯出資料 * @headlist 第一行列名(注意前兩個列名不能是大寫!否則輸出的副檔名不是cvs) * @fileName 輸出Excel檔名 */ function csv_export($data = array(), $headlist = array(), $fileName) {
header('Content-Type: application/vnd.ms-excel'); header('Content-Disposition: attachment;filename="'.$fileName.'.csv"'); header('Cache-Control: max-age=0');
//開啟PHP檔案控制代碼,php://output 表示直接輸出到瀏覽器 $fp = fopen('php://output', 'a');// 開啟檔案資源,不存在則建立
//輸出Excel列名資訊 foreach ($headlist as $key => $value) { //CSV的Excel支援GBK編碼,一定要轉換,否則亂碼 $headlist[$key] = iconv('utf-8', 'gbk', $value); }
//將資料通過fputcsv寫到檔案控制代碼 fputcsv($fp, $headlist);
//計數器 $num = 0;
//每隔$limit行,重新整理一下輸出buffer,不要太大,也不要太小 $limit = 100000;
//逐行取出資料,不浪費記憶體 $count = count($data); for ($i = 0; $i < $count; $i++) {
$num++;
//重新整理一下輸出buffer,防止由於資料過多造成問題 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); } }
方法二:
public function getExportLog(){ if (! $this->valid_admin ( @$_SERVER ['PHP_AUTH_USER'], @$_SERVER ['PHP_AUTH_PW'] )) {//$_SERVER ['PHP_AUTH_USER']瀏覽器接受的使用者名稱輸入 header ( 'WWW-Authenticate: Basic realm=""' );//瀏覽器彈出輸入使用者名稱密碼提示框 header ( 'HTTP/1.0 401 Unauthorized' ); echo "You need to enter a valid username and password."; exit (); }
$oViewLog = new DbsPatientViewLog(); $result = $oViewLog->getAllInfo(); $sname = time(); $dataname=date('Ymd'); $exportdir = public_path()."/exportfile/".$dataname."/"; if(!is_dir($exportdir)) { mkdir($exportdir,0777,true); } //生成csv檔案 $elsfile=$exportdir.$sname.'.csv'; $fp = fopen($elsfile, 'w'); $data=""; $title=implode(',', array('醫脈通加密ID','醫脈通ID','文章ID','參與的活動','訪問活動首頁的時間','訪問記錄資訊頁面的時間','參與活動的方式')); $data=$title; foreach($result as $value) { $line=implode(',', array($value['meduid_old'], $value['meduid'], $value['msgid'], $value['hd_way']==1?'疑似患者轉診':'DES試紙', $value['view_at'], $value['view_at_show'], $value['view_way']==1?'mobile':$value['view_way']==2?'微信瀏覽器': 'PC', ) ); $data=$data."\r\n".$line; } $data=iconv("UTF-8", "GBK//IGNORE", $data); fwrite($fp,$data); // 寫入資料 fclose($fp); //關閉檔案控制代碼 $download_dir= "/exportfile/".$dataname.'/'.$sname.'.csv'; header("Content-type:text/csv"); header("Content-Disposition:attachment;filename=".$sname.'.csv'); header('Cache-Control:must-revalidate,post-check=0,pre-check=0'); header('Expires:0'); header('Pragma:public'); echo $data; } -------------------------------------------------------------------------------------------------------------------------------------------------
流程:
1、使用fopen()函式,開啟指定檔案,不存在建立檔案
2、對標題進行處理,是陣列的話,可以像第一段程式碼一樣直接使用fputcsv()直接將資料寫到檔案控制代碼中去;或者使用第二段程式碼使用implode()函式分割
3、對資料的處理,第一段是將資料一行一行資料格式轉換後寫入檔案;第二段是implode()分割資料,資料整體最終拼接在一起,轉換格式寫入資料; 注:fwrite()寫入資料
4、關閉檔案控制代碼
總結:生成csv檔案流程就是如此,本人推薦第一種,省記憶體,且定期重新整理輸出buffer,防止資料過多造成的問題 --------------------------------------------------------------------------------------------------------------------------------------------------- 還有別的匯出功能方式: 第一種寫法: 檢視: onclick="window.location.href='/admin/video/export'" 控制器: set_time_limit(0); header('Cache-control:public'); header('Pragma:public'); header('Content-type:application/vnd.ms-excel'); header('Content-Disposition:attachment;filename=works_info_'.date('Ymdhis').'.csv'); header('Content-Type:APPLICATION/OCTET-STREAM'); ob_start(); $header_str=iconv('utf-8','gbk',"視訊id,視訊標題,視訊分類,專家姓名,專家專業,專家醫院,本期視訊觀看的總次數,本期視訊觀看的總時長\n"); $file_str=''; $oViodes=Video::All(); if ($oViodes){ foreach ($oViodes as $k=>$v){ $view_length=Viewlog::where('video_id',$v->id)->sum('video_length'); $file_str.=$v->id.','; $file_str.=$v->caption.','; $file_str.=$v->class.','; $file_str.=$v->expert_name.','; $file_str.=$v->profession.','; $file_str.=$v->hospital.','; $file_str.=isset($v->browse_count) ? $v->browse_count.',' : ''.','; $file_str.=isset($view_length) ? $view_length."\n" : ''."\n" ; } $file_str=iconv('utf-8','GBK//TRANSLIT',$file_str); ob_end_clean(); echo $header_str; echo $file_str; } 第二種寫法: 檢視: onclick="exportcsv()"
function exportcsv() { $.get("/admin/video/export",function(data) { window.location.href=data; window.event.returnValue = false;
}); }
控制器: $oVideos=Video::All(); $sname = time(); $dataname=date('Ymd'); $exportdir = public_path()."/exportfile/".$dataname."/"; if(!is_dir($exportdir)) { mkdir($exportdir,0777,true); } //生成csv檔案 $elsfile=$exportdir.$sname.'.csv'; $fp = fopen($elsfile, 'w'); $data=""; $title=implode(',', array('視訊id','視訊標題','視訊分類','專家姓名','專家專業','專家醫院','本期視訊觀看的總次數','本期視訊觀看的總時長')); $data=$title; foreach($oVideos as $cf) { $view_length=Viewlog::where('video_id','=',$cf->id)->sum('video_length'); $line=implode(',', array(isset($cf->id) ? $cf->id :'', isset($cf->caption) ? $cf->caption : '', isset($cf->class) ? $cf->class : '', isset($cf->expert_name) ? $cf->expert_name : '', isset($cf->profession) ? $cf->profession : '', isset($cf->hospital) ? $cf->hospital : '', isset($cf->browse_count) ? $cf->browse_count : '', isset($view_length) ? $view_length : '', )); $data=$data."\r\n".$line; } $data=mb_convert_encoding($data, "GBK", "UTF-8");//iconv("UTF-8", "GBK//IGNORE", $data); fwrite($fp,$data); // 寫入資料 fclose($fp); //關閉檔案控制代碼 $download_dir= "/exportfile/".$dataname.'/'.$sname.'.csv'; return $download_dir; --------------------- 作者:不二週助Rex 來源:CSDN 原文:https://blog.csdn.net/weixin_42188216/article/details/83899445 版權宣告:本文為博主原創文章,轉載請附上博文連結!