PHP打印Excel表格并下载
1、效果
2、代码
/**
* @todo 下载Excel
*/
public function downAction(){
$data = $this->getData(); //获取需要打印的数据
//打开请求头
$filename = "用户信息(".date("Ymd").")";
//设置浏览器信息
header("Content-type:application/vnd.ms-excel;charset=UTF-8");
header("Content-Disposition:filename=".$filename.".xls");
ob_clean(); //清空缓冲区
echo '<meta http-equiv="Content-Type" content="text/html; charset=GBK" />';
$content = '<table border="1" cellspacing="0">'; // width="70%"
$content .='<tr >';//style="font-size: 16px;font-weight: 800;"
$content .='<th align="center" height="30" width="120">'.mb_convert_encoding("用户ID",'GBK').'</th>';
$content .='<th align="center" height="30" width="120">'.mb_convert_encoding("用户名",'GBK').'</th>';
$content .='<th align="center" height="30" width="150">'.mb_convert_encoding("用户电话",'GBK').'</th>';
$content .='<th align="center" height="30" width="150">'.mb_convert_encoding("用户地址",'GBK').'</th>';
$content .='</tr>';
foreach ($data as $k => $v){
$content .='<tr>';
$content .='<td height="30" align="center">'.mb_convert_encoding($v['id'],'GBK').'</td>';
$content .='<td height="30" align="center">'.mb_convert_encoding($v['name'],'GBK').'</td>';
$content .='<td height="30" align="center">'.mb_convert_encoding($v['phone'],'GBK').'</td>';
$content .='<td height="30" align="center">'.mb_convert_encoding($v['address'],'GBK').'</td>';
$content .='</tr>';
}
$content .='</table>';
echo $content;
exit();
}
public function getData(){
$data = [];
for($i=1; $i<=10; $i++){
$data[] = ["id"=>$i, 'name'=>"姓名{$i}", "phone"=>"{$i}0*****", "address"=>"地址{$i}"];
}
return $data;
}