PHP 導出excel 數據量大時
阿新 • • 發佈:2018-08-15
nbsp 亂碼 編號 支持 sele des 數據庫配置 each -c
public function ceshiexcel1(){ set_time_limit(0); $filename = ‘病毒日誌‘; header(‘Content-Type: application/vnd.ms-excel‘); header(‘Content-Disposition: attachment;filename="‘.$filename.‘.csv"‘); header(‘Cache-Control: max-age=0‘); //原生鏈接mysql //數據庫配置 $mysql_conf = array(‘host‘ => ‘127.0.0.1:52971‘,‘db‘ => ‘center‘, ‘db_user‘ => ‘root‘, ‘db_pwd‘ => ‘‘);$mysql_conn = @mysql_connect($mysql_conf[‘host‘], $mysql_conf[‘db_user‘], $mysql_conf[‘db_pwd‘]); if (!$mysql_conn) { die("could not connect to the database:\n" . mysql_error());//診斷連接錯誤 } $select_db = mysql_select_db($mysql_conf[‘db‘]); if (!$select_db) {die("could not connect to the db:\n" . mysql_error()); } $sql = M(‘logvirus‘) ->alias(‘a‘) ->fetchsql() ->field(‘a.id,a.strVirusName,c.address,c.rmaker,a.nVirusType,a.nunknowvirustype,a.strVirusPath,a.VirusTime,a.nunknownflag,a.terminal,d.name as rname,(case when a.iHigh_DiskType=0 then a.iLow_DiskType else a.iHigh_DiskType end) as idisktypes‘)//f.iDiskTypes,j.name as iname ->join(‘LEFT JOIN sysinfo c ON c.terminal = a.terminal‘) ->join(‘LEFT JOIN pm_dealresult d ON d.mask = a.nDealResult‘) // ->where($where) ->order("a.VirusTime desc") ->limit(‘1,10‘) ->select(); $head = array( ‘id‘=>‘編號‘, ‘strvirusname‘=>‘病毒名稱‘, ‘address‘=>‘終端IP‘, ‘rmaker‘=>‘別名‘, ‘nname‘=>‘病毒類型‘, ‘iname‘=>‘威脅來源‘, ‘strviruspath‘=>‘病毒路徑‘, ‘rname‘=>‘處理結果‘, ‘virustime‘=>‘時間‘ ); $stmt = mysql_query($sql); /*echo "<pre/>"; while ($row = mysql_fetch_array($stmt,MYSQL_ASSOC)) { foreach ($row as $i => $v) { $row[$i] = iconv(‘utf-8‘, ‘gb2312‘, $v); var_dump($row); } } exit;*/ // 打開PHP文件句柄,php://output 表示直接輸出到瀏覽器 $fp = fopen(‘php://output‘, ‘a‘); // 輸出Excel列名信息 //$head = array(‘id‘, ‘casenum‘, ‘terminal‘, ‘strVirusMd5‘,‘nVirusType‘,‘nVirusCode‘,‘nOldVirusCode‘); foreach ($head as $i => $v) { // CSV的Excel支持GBK編碼,一定要轉換,否則亂碼 $head[$i] = iconv(‘utf-8‘, ‘gb2312‘, $v); } // 將數據通過fputcsv寫到文件句柄 fputcsv($fp, $head); // 計數器 $cnt = 0; // 每隔$limit行,刷新一下輸出buffer,不要太大,也不要太小 $limit = 100000; // 逐行取出數據,不浪費內存 $data = array(); while ($row = mysql_fetch_array($stmt,MYSQL_ASSOC)) { $cnt ++; if ($limit == $cnt) { //刷新一下輸出buffer,防止由於數據過多造成問題 ob_flush(); //釋放 flush(); $cnt = 0; } foreach ($row as $i => $v) { //$row[$i] = iconv(‘utf-8‘, ‘gb2312‘, $v); $data[‘id‘] = $cnt; $data[‘strvirusname‘] = iconv(‘utf-8‘, ‘gb2312‘, $row[‘strVirusName‘]); $data[‘address‘] = iconv(‘utf-8‘, ‘gb2312‘, $row[‘address‘]); $data[‘rmaker‘] =iconv(‘utf-8‘, ‘gb2312‘, $row[‘VirusTime‘]); $data[‘nname‘] =iconv(‘utf-8‘, ‘gb2312‘, $row[‘VirusTime‘]); $data[‘iname‘] =iconv(‘utf-8‘, ‘gb2312‘, $row[‘VirusTime‘]); $data[‘strviruspath‘] =iconv(‘utf-8‘, ‘gb2312‘, $row[‘VirusTime‘]); $data[‘rname‘] = $row[‘rname‘] ; $data[‘virustime‘] =iconv(‘utf-8‘, ‘gb2312‘, $row[‘VirusTime‘]); } fputcsv($fp, $data); } //關閉數據庫 mysql_close($mysql_conn); }
PHP 導出excel 數據量大時