PHP导出excel文件的几种方式
先说说动态生成的内容当作文件来下载的方法:
1、通过把Content-Type设置为application/octet-stream,可以把动态生成的内容当作文件来下载;
2、用Content-Disposition设置下载的文件名;
3、 基本上,下载程序都是这么写的:
<?php $filename = "document.txt"; header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename=' . $filename); print "Hello!"; ?>
4、当然要考虑到浏览器兼容性和对如果文件名是中文的话出现异常bug,我们这么写:
<?php $ua = $_SERVER["HTTP_USER_AGENT"]; $filename = "文件名.txt"; $encoded_filename = urlencode($filename); $encoded_filename = str_replace("+", "%20", $encoded_filename); header('Content-Type: application/octet-stream'); if (preg_match("/MSIE/", $ua)) { header('Content-Disposition: attachment; filename="' . $encoded_filename . '"'); } else if (preg_match("/Firefox/", $ua)) { header('Content-Disposition: attachment; filename*="utf8\'\'' . $filename . '"'); } else { header('Content-Disposition: attachment; filename="' . $filename . '"'); } print 'ABC'; ?>
导出excel文件
1、原始方式:发送header,用附件的表头发送到用户浏览器表示是要下载的,然后读出数据库中的数据,一条一条的解析,写入excel格式的文件中。
$mysql_server_name = 'localhost'; //改成自己的mysql数据库服务器 $mysql_username = 'admin'; //改成自己的mysql数据库用户名 $mysql_password = 'p1234567'; //改成自己的mysql数据库密码 $mysql_database = 'tp6demo'; //改成自己的mysql数据库名 $conn=@mysqli_connect($mysql_server_name,$mysql_username,$mysql_password,$mysql_database); //连接数据库 //连接数据库错误提示 if (mysqli_connect_errno($conn)) { die("连接 MySQL 失败: " . mysqli_connect_error()); } mysqli_query($conn,"set names gbk"); //数据库编码格式 // mysqli_set_charset($conn,"utf8");//设置默认客户端字符集。 // mysqli_select_db($conn,$mysql_database); //更改连接的默认数据库 $file_type = "vnd.ms-excel"; $file_ending = "xls"; $savename = date('Y-m-d'); header("Content-Type: application/$file_type;charset=utf8"); header("Content-Disposition: attachment; filename=".$savename.".$file_ending"); $sep = "\t"; //查询代码 //SELECT `tel` FROM `users` WHERE `data` < 20201203 GROUP BY `tel` ORDER BY `users`.`data` DESC LIMIT 100 $sql = "SELECT `username`,`email` FROM `tp_user` GROUP BY `username` LIMIT 12"; $query = mysqli_query($conn,$sql); $content .= 'username'.$sep.'email'."\r"; while($row = mysqli_fetch_array($query)){ $content .= $row['username'].$sep.$row['email']."\r"; } // 释放结果集+关闭MySQL数据库连接 @mysqli_free_result($result); @mysqli_close($conn); exit($content);