1 /**excel导出数据 2 * @param $xlsName 文件名称 3 * @param array $titleArr 文件标题 4 * @param array $dataArr 数据 5 */ 6 function excel_out($xlsName, array $titleArr, array $dataArr) { 7 if (empty($titleArr) || empty($dataArr)) { 8 die('error'); 9 } 10 date_default_timezone_set('PRC');//设置时区 11 set_time_limit(0); 12 //设置header头信息 13 Header("Content-Type:application/vnd.ms-excel;charset=UTF-8"); 14 Header("Accept-Ranges:bytes"); 15 Header("Content-Disposition:attachment;filename=".$xlsName.'_'.date('YmdHis').".xls"); 16 Header("Pragma:no-cache"); 17 Header("Expires:0"); 18 19 $str = $str2 = ''; 20 foreach ($titleArr as $field => $name) { 21 $str .= trim(iconv("UTF-8","GBK", $name)) ."\t"; 22 } 23 $str .= "\r\n"; 24 echo $str; 25 foreach ($dataArr as $k => $v) { 26 foreach ($titleArr as $field => $name) { 27 $str2 .= trim(iconv("UTF-8","GBK", $v[$field]))."\t"; 28 } 29 $str2 .= "\r\n"; 30 } 31 echo $str2; 32 die; 33 }
使用示例:
$res = array( array("name"=>'张三','sex'=>'男','age'=>20,'tel'=>'17895623145','id_number'=>"15616619941025152X"), array("name"=>'李四','sex'=>'女','age'=>25,'tel'=>'17895623145','id_number'=>"156166199410251520"), array("name"=>'王五','sex'=>'男','age'=>20,'tel'=>'17895623145','id_number'=>"156166199410251528"), ); $xlsName = '用户信息表'; $xlsCell = ['name'=>'姓名','sex'=>'性别','age'=>'年龄','tel'=>'手机号','id_number'=>'身份证号']; foreach ($res as $key=>&$val) { //防止数字过长 变成科学计数法 1.56166E+17 $val['tel'] = ':'.$val['tel'] ; $val['id_number'] = ':'.$val['id_number']; } excel_out($xlsName, $xlsCell, $res);
这样的excel就导出下来喽……见下图