php生成Excel文件 實(shí)現(xiàn)代碼

字號:


    <p>有段日子沒有更新博客了,生怕被百度遺忘啊,biu~biu~.最近有個(gè)項(xiàng)目需要統(tǒng)計(jì)網(wǎng)站的url和title,保存在excel里面,下面是具體的代碼</p>
    <pre name="code"><!--p
    //php生成excel報(bào)表,是通過發(fā)送header()頭信息完成的
    header("Content-Type: application/vnd.ms-execl");
    header("Content-Type: application/vnd.ms-excel; charset=gb2312");
    //告知瀏覽器文件名稱,并要求客戶端下載
    header("Content-Disposition:filename=test.xls");
    header("Pragma: no-cache");
    header("Expires: 0");
    $link = mysql_connect('localhost', 'root', '') or die('Could not connect: ' . mysql_error());
    mysql_select_db('novartis') or die('Could not select database');
    mysql_query("SET NAMES gb2312");
    $query = 'SELECT title,keywords,url,description FROM cms_content';
    $result = mysql_query($query) or die('Query failed: ' . mysql_error());
    // 用 HTML 顯示結(jié)果
    //$str =mb_convert_encoding ("測試1","gb2312","utf-8");
    echo "Title\t";
    echo "Keywords\t";
    echo "Description\t";
    echo "URL\t\n";
    /* 格式: 換行:"\t\n": 單元格之間: "\t" */
    while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
    echo $line['title']."\t";
    echo $line['keywords']."\t";
    echo $line['description']."\t";
    echo $line['url']."\t\n";
    }
    // 釋放結(jié)果集
    mysql_free_result($result);
    // 關(guān)閉連接
    mysql_close($link);
    -->
    </pre>
    <div>&nbsp;</div>