Home >Backend Development >PHP Tutorial >PHP header function exports excel table
In addition to exporting tables using PHPExcel, we recommend another simple table import method that does not require the introduction of class files - header() to export excel tables.
The steps to export the table are encapsulated into methods for easy reuse. The code is as follows:
1 /** 2 * 导出数据为excel表格 3 *@param $data 一个二维数组,结构如同从数据库查出来的数组 4 *@param $title excel的第一行标题,一个数组,如果为空则没有标题 5 *@param $filename 下载的文件名 6 *@examlpe10 */11 function exportexcel($data=array(),$title=array(),$filename='report'){12 ob_end_clean(); 13 ob_start(); 14 header("Content-type:application/octet-stream");15 header("Accept-Ranges:bytes");16 header("Content-type:application/vnd.ms-excel");17 header("Content-Disposition:attachment;filename=".$filename.".xls");18 header("Pragma: no-cache");19 header("Expires: 0");20 //导出xls 开始21 if (!empty($title)){22 foreach ($title as $k => $v) {23 $title[$k]=iconv("UTF-8", "GB2312",$v);24 }25 $title= implode("\t", $title);26 echo "$title\n";27 }28 if (!empty($data)){29 foreach($data as $key=>$val){30 foreach ($val as $ck => $cv) {31 $data[$key][$ck]=iconv("UTF-8", "GB2312", $cv);32 }33 $data[$key]=implode("\t", $data[$key]);34 }35 echo implode("\n",$data);36 }37 }
A simple example
1 $data =M ('User')-> select();2 $title = array('id','账户','密码','昵称');3 exportexcel($data,$title,'用户表!');
The ob_end_clean() and ob_start() functions in the method are mainly used to clear cache and boom headers to prevent garbled characters and format errors. If you need to do an export operation, just define a two-dimensional array and a header array and then directly call the download.
Original: http://www.cnblogs.com/luokakale/p/8352517.html
Related recommendations:
Super practical PHPExcel [import][export] implementation method summary-CSDN blog
The above is the detailed content of PHP header function exports excel table. For more information, please follow other related articles on the PHP Chinese website!