php生成excel文件

发布时间:2009-10-13 21:31:06 阅读:1215次

转自:http://hi.baidu.com/34pc/blog/item/50e6b1fa036726dcb58f314e.htmlphp
1、不用COM,生成excel文件
<?
header("Content-type:application/vnd.ms-excel");
header("Content-Disposition:filename=test.xls");
echo "列一\t列二\t列三\r\n";
echo "test1\t";
echo "test2\t";
echo "test3\r\n";
?>
  在php环境运行上面的代码,大家就可以看到浏览器询问用户是否下载excel文档,点击保存,硬盘上就多了一个excel的文件,使用excel打开就会看到最终的结果,怎么样不错吧。
  其实在做真正的应用的时候,大家可以将数据从数据库中取出,然后按照每一列数据结束后加\t,每一行数据结束后加\r\n的方法echo出来,在php的开头用header("Content-type:application/vnd.ms-excel");表示输出的是excel文件,用header("Content-Disposition:filename=test.xls");表示输出的文件名为text.xls。这样就ok了。
  我们更可以修改header让他输出更多格式的文件,这样php在处理各种类型文件方面就更加方便了。
2、用PHP将mysql数据表转换为excel文件格式
<?
include "conn.php";
$dd=1;
 $sql2="select * from userinfo where addtime>='".$_POST["datefrom"]." 00:00:00' and addtime<='".$_POST["dateto"]." 23:59:59'   order by addtime desc ";
 $sql = qeeka_query($sql2,$db);
 //echo $sql2;
 if($myrow = mysql_fetch_array($sql)){
  header("Content-type:application/vnd.ms-excel");
header("Content-Disposition:filename=qbsbooks.xls");
  echo("序号\t姓名\t性别\t年龄\t出生日期\t添加日期\r\n");
  do{
   $id=$myrow["id"];
   $username=$myrow["username"];
   $sex=$myrow["sex"];
   $age=$myrow["age"];
   $birthday=$myrow["birthday"];
   $addtime=$myrow["addtime"];
   echo $dd.\t;
   echo$username;
   echo "\t";
   echo $sex;
   echo "\t ";
   echo $age;
   echo "\t";
   echo $birthday;
   echo "\t";
   echo $addtime;
   echo "\r\n";
   $dd++;
  }while($myrow = mysql_fetch_array($sql));
 }
?>

如有问题,可以QQ搜索群1028468525加入群聊,欢迎一起研究技术

支付宝 微信

有疑问联系站长,请联系QQ:QQ咨询

转载请注明:php生成excel文件 出自老鄢博客 | 欢迎分享