2016年3月23日 16:43:51 星期三
第一种: 输出html+css格式, 打开后用Excel软件的"另存为"功能保存为正规的表格格式
1 public function echoExcel($list) 2 { 3 $body = \'\'; 4 $tr = \'<tr style="border-right: 1px solid lightgrey;border-bottom: 1px solid lightgrey;">\'; 5 $tds = \'<td>\'; 6 $tde = \'</td>\'; 7 8 $title = $tr.\'<td>aaa</td> 9 <td>bbb</td> 10 </tr>\'; 11 $userModel = new UserModel(); 12 foreach ($list as $v) { 13 $aaa = $tds.$v[\'aaa\'].$tde; 14 $bbb = $tds.$v[\'bbb\'].$tde; 15 $body .= $tr.$aaa.$bbb.\'</tr>\'; 16 } 17 18 header(\'Content-Type: application/vnd.ms-excel\'); 19 header(\'Content-Disposition: attachment;filename="\'.date(\'Y_m_d_H_i_s\').\'.xls"\'); 20
21 $table = \'<table style="border: 1px solid lightgrey; border-collapse: collapse;">\'; 22 echo $table.$title.$body.\'</table>\'; 23 exit; 24 }
注意: mac打不开, mac与windows打开excel的软件不同
windows打开后可以另存为正规格式的excel
第二种: 不用css, 只用逗号, 以csv的方式输出
1 function export() 2 { 3 $list = [ 4 [\'1111\', \'2222\'], 5 [\'1111\', \'2222\'], 6 ]; 7 $content = \'aaa,bbb\'.PHP_EOL;//csv标题 8 foreach ($list as $line) { 9 $content .= implode(\',\', $line).PHP_EOL; 10 } 11 12 //下载文件需要用到的头 13 header(\'Content-type: application/octet-stream\'); 14 header(\'Accept-Ranges: bytes\'); 15 header(\'Accept-Length:\' . strlen($content)); 16 header(\'Content-Disposition: attachment; filename=\'.date(\'YmdHis\').\'.csv\'); 17 echo "\xEF\xBB\xBF"; //utf-8 bom 18 echo $content; 19 }
注意, 使用的时候, 在新窗口打开, 不要用ajax请求:
<a href="/export" target="_blank">