网站首页 语言 会计 互联网计算机 医学 学历 职场 文艺体育 范文
当前位置:学识谷 > 计算机 > php语言

php操作excel文件的方法小结

栏目: php语言 / 发布于: / 人气:2.41W

php操作excel文件的方法有哪些?就跟随本站小编一起去了解下吧,想了解更多相关信息请持续关注我们应届毕业生考试网!

php操作excel文件的方法小结

  一、php,不用COM,生成excel文件

复制代码 代码如下:

<?

header("Content-type:application/-excel");

header("Content-Disposition:filename=");

echo "test1t";

echo "test2tn";

echo "test1t";

echo "test2tn";

echo "test1t";

echo "test2tn";

echo "test1t";

echo "test2tn";

echo "test1t";

echo "test2tn";

echo "test1t";

echo "test2tn";

?>

在php环境运行上面的代码,大家就可以看到浏览器询问用户是否下载excel文档,点击保存,硬盘上就多了一个excel的`文件,使用excel打开就会看到最终的结果,怎么样不错吧。

其实在做真正的应用的时候,大家可以将数据从数据库中取出,然后按照每一列数据结束后加t,每一行数据结束后加n的方法echo出来,在php的开头用header("Content-type:application/-excel");表示输出的是excel文件,用header("Content-Disposition:filename=");表示输出的文件名为。这样就ok了。

我们更可以修改header让他输出更多格式的文件,这样php在处理各种类型文件方面就更加方便了.

  二、用PHP将mysql数据表转换为excel文件格式

复制代码 代码如下:

<?php

$DB_Server = "localhost";

$DB_Username = "mydowns";

$DB_Password = "";

$DB_DBName = "mydowns";

$DB_TBLName = "user";

$Connect = @mysql_connect($DB_Server, $DB_Username, $DB_Password)

or die("Couldn@#t connect.");

$Db = @mysql_select_db($DB_DBName, $Connect)

or die("Couldn@#t select database.");

$file_type = "-excel";

$file_ending = "xls";

header("Content-Type: application/$file_type");

header("Content-Disposition: attachment; filename=mydowns.$file_ending");

header("Pragma: no-cache");

header("Expires: 0");

$now_date = date(@#Y-m-d H:i@#);

$title = "数据库名:$DB_DBName,数据表:$DB_TBLName,备份日期:$now_date";

$sql = "Select * from $DB_TBLName";

$ALT_Db = @mysql_select_db($DB_DBName, $Connect)

or die("Couldn@#t select database");

$result = @mysql_query($sql,$Connect)

or die(mysql_error());

echo("$titlen");

$sep = "t";

for ($i = 0; $i < mysql_num_fields($result); $i++) {

echo mysql_field_name($result,$i) . "t";

}

print("n");

$i = 0;

while($row = mysql_fetch_row($result))

{