1. 程式人生 > >PHP列印Excel表格並下載

PHP列印Excel表格並下載

                                                                            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;
	}