现在,很多地方都需要导出数据,这里说一种简单的方法将数据以Excel的形式导出,方法如下:
<?php
date_default_timezone_set('PRC');//设置时区 /*设置head头信息*/
Header("Content-Type:application/vnd.ms-excel;charset=UTF-8");
Header("Accept-Ranges:bytes");
Header("Content-Disposition:attachment;filename=".date('YmdHis').".xls");
Header("Pragma:no-cache");
Header("Expires:0"); $str = $str2 = null;
/*设置表格信息*/
$str.= "ID"."\t";
$str.= "用户名"."\t";
$str.= "密码"."\t";
$str.= "邮箱"."\t\r\n";
$info = iconv("UTF-8","GBK",$str);
echo $info; /*查询内容导出数据库数据*/
$link = @mysql_connect('localhost','root','') or die('Failed to connect to the MySQL');
mysql_select_db('l_test',$link);
mysql_set_charset('utf8',$link);
$query = 'select * from lt_user';
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)){
$list[] = $row;
}
mysql_free_result($result);
mysql_close($link); foreach($list as $v){
$str2.= trim(iconv("UTF-8","GBK",$v['id']))."\t";
$str2.= trim(iconv("UTF-8","GBK",$v['username']))."\t";
$str2.= trim(iconv("UTF-8","GBK",$v['passwd']))."\t";
$str2.= trim(iconv("UTF-8","GBK",$v['email']))."\t\r\n";
}
echo $str2;
?>
这个方法相对简单,但在一些小的程序上,作为一个简单的方法还是不错的,希望能对大家有所帮助。