php輸出excel的簡單方法(csv格式)

在php中有專業的excel處理類我們可以用它來增加,刪除或處理excel中相關資料,如果我們只是要產生excel就可以使用下面方法簡單又快捷。

如果不讀資料我們直接使用下面程式碼就可以了,只需要把相關的資料導出到excel表就可以了,這麼簡單的操作就不需要用那些類庫什麼的了。直接用header的方式就可以了:header("Content-type:application/vnd.ms-excel");
 程式碼如下

<?php
header("Content-type:application/vnd.ms-excel");
header("Content-Disposition: attachment;filename=yingcai.xls");
?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
    <table border="1">
        <tr>
            <td>用戶名</td>
            <td>密碼</td>
        </tr>
        <tr>
            <td>admin</td>
            <td>yingcai</td>
        </tr>
    </table>
</body>
</html>


簡單純粹的php導出excel表格方法,木有過多的解釋,花哨的裝飾,一看就懂
 程式碼如下     複製程式碼


header("Content-type:application/vnd.ms-excel");
header("Content-Disposition:attachment; filename=用戶信息表.xls");
require_once('./class.db.php');
$db = new DB('localhost', 'app_vmovies', 'root', '123456');
$sql = 'select * from `user` order by `id` desc';
$ret = $db->get_results($sql);

// 輸出內容如下:  
echo "ID"."t";
echo "暱稱"."t";
echo "性別"."t";
echo "OpenId"."t";
echo "平台"."t";
echo "註冊日期"."t";
echo "n";

$len = count($ret);
for ( $i = 0; $i < $len; $i++ ) {
    echo $ret[$i]["id"]."t";
    echo $ret[$i]["nickname"]."t";
    echo $ret[$i]["gender"]."t";
    echo $ret[$i]["openid"]."t";
    echo $ret[$i]["pf"]."t";
    echo $ret[$i]["regdate"]."t";
    echo "n";
}

如果程式是utf-8編碼的,還需要用iconv函數去轉碼,不然是會亂碼的,亂碼的。

另word格式導入類似,,指定header就可以了:
 程式碼如下     複製程式碼

header("Content-Type:   application/msword");      
header("Content-Disposition:   attachment;   filename=doc.doc");

留言

這個網誌中的熱門文章

c語言-關於#define用法

CMD常用網管指令

PHP 與 JavaScript 之間傳值利用 json