PHP 导出excel 数据量大时
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); }