现在的位置: 首页 -> PHP学习 -> PHP源码 -> php将数据表中的数据导出到excel表

php将数据表中的数据导出到excel表

2014-03-03 22:45评论数 2 ⁄ 被浏览 10244 views+

很多时候,数据库中的数据需要导出成excel,以下是最简便的方法,不用导出excel的类,即使功能简单,但是对于没有复杂需求的项目“见效快”。


先定义头部信息,表示输出一个excel。然后再以table的形式把数据库的信息循环的echo出来,就好了。


<?php

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

header("Content-Disposition:filename=xls_region.xls");

$cfg_dbhost = 'localhost';

$cfg_dbname = 'testdb';

$cfg_dbuser = 'root';

$cfg_dbpwd = 'root';

$cfg_db_language = 'utf8';

// END 配置


//链接数据库

$link = mysql_connect($cfg_dbhost,$cfg_dbuser,$cfg_dbpwd);

mysql_select_db($cfg_dbname);

//选择编码

mysql_query("set names ".$cfg_db_language);

//users表

$sql = "desc users";

$res = mysql_query($sql);

echo "<table><tr>";

//导出表头(也就是表中拥有的字段)

while($row = mysql_fetch_array($res)){

$t_field[] = $row['Field']; //Field中的F要大写,否则没有结果

echo "<th>".$row['Field']."</th>";

}

echo "</tr>";

//导出100条数据

$sql = "select * from users limit 100";

$res = mysql_query($sql);

while($row = mysql_fetch_array($res)){

echo "<tr>";

foreach($t_field as $f_key){

echo "<td>".$row[$f_key]."</td>";

}

echo "</tr>";

}

echo "</table>";

?>


 

文章出自:https://www.daixiaorui.com/read/74.html 本站所有文章,除注明出处外皆为原创,转载请注明本文地址,版权所有。

目前有 2 条评论  @我要评论

  1. 2楼宋齐梁 : 2017-11-09 09:44:20 评论说: @回复

    写的非常棒,很受用

    回复留言标识 宋齐梁 回复 宋齐梁: 看一下你的回复

    2017-11-09 10:16:10  @回复

  2. 1楼Jochen : 2016-07-01 10:32:42 评论说: @回复

    你写的分享都很用心,值得学习!

您的每一个评论都是对我的一份支持

 博客二维码

昵称 *

邮箱 *