php操作excel文件的方法小結

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))

{