PHP导出excel文件的几种方式
先说说动态生成的内容当作文件来下载的方法:
1、通过把Content-Type设置为application/octet-stream,可以把动态生成的内容当作文件来下载;content-type内容设置可以参看:
http://www.ostools.net/commons
2、用Content-Disposition设置下载的文件名;
3、 基本上,下载程序都是这么写的:
1 <?php 2 $filename = "document.txt"; 3 header('Content-Type: application/octet-stream'); 4 header('Content-Disposition: attachment; filename=' . $filename); 5 print "Hello!"; 6 ?>
4、当然要考虑到浏览器兼容性和对如果文件名是中文的话出现异常bug,我们这么写:
1 <?php 2 $ua = $_SERVER["HTTP_USER_AGENT"]; 3 $filename = "文件名.txt"; 4 $encoded_filename = urlencode($filename); 5 $encoded_filename = str_replace("+", "%20", $encoded_filename); 6 header('Content-Type: application/octet-stream'); 7 if (preg_match("/MSIE/", $ua)) { 8 header('Content-Disposition: attachment; filename="' . $encoded_filename . '"'); 9 } else if (preg_match("/Firefox/", $ua)) { 10 header('Content-Disposition: attachment; filename*="utf8\'\'' . $filename . '"'); 11 } else { 12 header('Content-Disposition: attachment; filename="' . $filename . '"'); 13 } 14 print 'ABC'; 15 ?>
明白了这些之后,生成excel就很简单了,处理下下载文档格式,解析数据,balabala就好了,看看怎么生成一篇excel的文档吧:
1、原始方式:发送header,用附件的表头发送到用户浏览器表示是要下载的,然后读出数据库中的数据,一条一条的解析,写入excel格式的文件中。
1 <?php 2 $DB_Server = "localhost"; 3 $DB_Username = "root"; 4 $DB_Password = ""; 5 $DB_DBName = "DBName"; 6 $DB_TBLName = "DB_TBLName"; 7 $savename = date("YmjHis"); 8 $Connect = @mysql_connect($DB_Server, $DB_Username, $DB_Password) or die("Couldn't connect."); 9 mysql_query("Set Names 'gbk'"); 10 $file_type = "vnd.ms-excel"; 11 $file_ending = "xls"; 12 header("Content-Type: application/$file_type;charset=gbk"); 13 header("Content-Disposition: attachment; filename=".$savename.".$file_ending"); 14 header("Pragma: no-cache"); 15 $now_date = date("Y-m-j H:i:s"); 16 $title = "数据库名:$DB_DBName,数据表:$DB_TBLName,备份日期:$now_date"; 17 $sql = "Select * from $DB_TBLName"; 18 $ALT_Db = @mysql_select_db($DB_DBName, $Connect) or die("Couldn't select database"); 19 $result = @mysql_query($sql,$Connect) or die(mysql_error()); 20 echo("$title\n"); 21 $sep = "\t"; 22 for ($i = 0;$i < mysql_num_fields($result);$i++) 23 { 24 echo mysql_field_name($result,$i) . "\t"; 25 } 26 print("\n"); 27 $i = 0; 28 while($row = mysql_fetch_row($result)) 29 { 30 $schema_insert = ""; 31 for($j=0; $j<mysql_num_fields($result);$j++) 32 { 33 if(!isset($row[$j])) $schema_insert .= "NULL".$sep; 34 elseif ($row[$j] != "") $schema_insert .= "$row[$j]".$sep; 35 else $schema_insert .= "".$sep; 36 } 37 $schema_insert = str_replace($sep."$", "", $schema_insert); 38 $schema_insert .= "\t"; 39 print(trim($schema_insert)); 40 print "\n"; $i++; 41 } 42 return (true); 43 ?>
2、用PHPExcel库
下面是用PHPExcel实现的与上面功能相同的excel的方法。getCol为递归实现的函数,用于根据数字返回对应的列号编码。因为导出的过程中需要指出行号,列号。行号为简单的数字,而列号则为“A-Z”的组合。为了方便二维数组的导入,根据列数自动得到列号编码。如“5”->“E”、“27”->“AZ”。
1 //设置PHPExcel类库的include path 2 $dirToLib1='./resource/PHPExcel1.7.0/Classes'; 3 ini_set('include_path', ini_get('include_path').PATH_SEPARATOR.$dirToLib1); 4 5 function getCol($num){//递归方式实现根据列数返回列的字母标识 6 $arr=array(0=>'Z',1=>'A',2=>'B',3=>'C',4=>'D',5=>'E',6=>'F',7=>'G',8=>'H',9=>'I',10=>'J',11=>'K',12=>'L',13=>'M',14=>'N',15=>'O',16=>'P',17=>'Q',18=>'R',19=>'S',20=>'T',21=>'U',22=>'V',23=>'W',24=>'X',25=>'Y',26=>'Z'); 7 if($num==0) 8 return ''; 9 return $this->getCol((int)(($num-1)/26)).$arr[$num%26]; 10 } 11 function exportToExcel($header,$data,$fileName){ 12 //利用PHPExcel工具进行导出,功能强大,格式规范,可导出2007 13 $fileName=$this->UTF8ToGBK($fileName); 14 $objExcel = new PHPExcel(); 15 $objWriter = new PHPExcel_Writer_Excel5($objExcel); 16 $objExcel->setActiveSheetIndex(0); 17 $objActSheet = $objExcel->getActiveSheet(); 18 //设置当前活动sheet的名称 19 //$objActSheet->setTitle('测试Sheet'); 20 //************************************* 21 //设置单元格内容 22 $i=1; 23 foreach ($header as $key => $value){ 24 $objActSheet->setCellValueExplicit($this->getCol($i).'1', $value,PHPExcel_Cell_DataType::TYPE_STRING); 25 //************************************* 26 //设置单元格样式 27 $objStyle = $objActSheet->getStyle($this->getCol($i++).'1'); 28 //设置边框 29 $objBorder = $objStyle->getBorders(); 30 $objBorder->getTop()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN); 31 $objBorder->getTop()->getColor()->setARGB('FFDDDDDD'); $objBorder->getBottom()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN); 32 $objBorder->getBottom()->getColor()->setARGB('FFDDDDDD'); 33 $objBorder->getLeft()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN); 34 $objBorder->getLeft()->getColor()->setARGB('FFDDDDDD'); // color 35 $objBorder->getRight()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN); 36 $objBorder->getRight()->getColor()->setARGB('FFDDDDDD'); // color 37 //设置填充颜色 38 $objFill = $objStyle->getFill(); 39 $objFill->setFillType(PHPExcel_Style_Fill::FILL_SOLID); 40 $objFill->getStartColor()->setARGB('FF00EEEE'); 41 } 42 $i=1; 43 foreach ($data as $row){ 44 $i++; 45 $j=1; 46 foreach ($header as $key => $value){ 47 $objActSheet->setCellValueExplicit($this->getCol($j++).$i, $row[$key],PHPExcel_Cell_DataType::TYPE_STRING); 48 } 49 } 50 //************************************* 51 //输出内容 52 //到浏览器 53 header("Content-Type: application/force-download"); 54 header("Content-Type: application/octet-stream"); 55 header("Content-Type: application/download"); 56 header('Content-Disposition:inline;filename="'.$fileName.'.xls"'); 57 header("Content-Transfer-Encoding: binary"); 58 header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); 59 header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); 60 header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 61 header("Pragma: no-cache"); 62 $objWriter->save('php://output'); 63 }
3、用PHPExcel等库,确实比较容易实现,但对大量数据的支持很不好,很容易到达PHP内存使用上限。这里的方法是利用fputcsv写CSV(这是一种逗号分隔值文件格式,见http://baike.baidu.com/view/468993.htm)文件的方法,直接向浏览器输出Excel文件:
1 <?php 2 // 输出Excel文件头,可把user.csv换成你要的文件名 3 header('Content-Type: application/vnd.ms-excel'); 4 header('Content-Disposition: attachment;filename="user.csv"'); 5 header('Cache-Control: max-age=0'); 6 // 从数据库中获取数据,为了节省内存,不要把数据一次性读到内存,从句柄中一行一行读即可 7 $sql = 'select * from tbl where ……'; 8 $stmt = $db->query($sql); 9 // 打开PHP文件句柄,php://output 表示直接输出到浏览器 10 $fp = fopen('php://output', 'a'); 11 // 输出Excel列名信息 12 $head = array('姓名', '性别', '年龄', 'Email', '电话', '……'); 13 foreach ($head as $i => $v) { 14 // CSV的Excel支持GBK编码,一定要转换,否则乱码 15 $head[$i] = iconv('utf-8', 'gbk', $v); 16 } 17 // 将数据通过fputcsv写到文件句柄 18 fputcsv($fp, $head); 19 // 计数器 20 $cnt = 0; 21 // 每隔$limit行,刷新一下输出buffer,不要太大,也不要太小 22 $limit = 100000; 23 // 逐行取出数据,不浪费内存 24 while ($row = $stmt->fetch(Zend_Db::FETCH_NUM)) { 25 $cnt ++; 26 if ($limit == $cnt) { 27 //刷新一下输出buffer,防止由于数据过多造成问题 28 ob_flush(); 29 flush(); 30 $cnt = 0; 31 } 32 33 foreach ($row as $i => $v) { 34 $row[$i] = iconv('utf-8', 'gbk', $v); 35 } 36 fputcsv($fp, $row); 37 }