PHP 数据导出表格格式excel
<?php
//php数据导出 excel 类型文件
header("Content-type:text/html;charset=uft-8");
mysql_connect('localhost','root','root');
mysql_select_db('test');
mysql_query('set names utf8');
export_csv(); function export_csv() {
$filename = 'fh_'.date('YmdHis').".csv";//文件名
header("Content-type:text/csv");
header("Content-Disposition:attachment;filename=".$filename);
header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
header('Expires:0');
header('Pragma:public');
echo array_to_string(get_export_data());
}
function i($strInput) {
return iconv('utf-8','gb2312',$strInput);//页面编码为utf-8时使用,否则导出的中文为乱码
}
function array_to_string($result) {
if(empty($result)) {
return i("没有符合您要求的数据!");
}
//表头
$data = iconv( 'utf-8', 'gb2312', "用户ID,用户名,年龄")."\r\n";
// 总记录条数
$size_result = sizeof($result);
//,商家留言 .
for($i = 0 ; $i < $size_result ; $i++) {
$data .=i($result[$i]['id']).','.
i($result[$i]['name']).','.
i($result[$i]['age'])."\n";
}
return $data;
}
function get_export_data() {
$sql = 'select id,name,age from user limit 10000';
$result = mysql_query($sql);
$res = array();
$i = 0;
while(!!$row = mysql_fetch_array($result)) {
$res[$i]['id'] = $row['id'];
$res[$i]['name'] = $row['name'];
$res[$i]['age'] = $row['age'];
$i++;
}
return $res;
}
改动源码来自:慕课网
http://www.imooc.com/article/6347
Dcr163的博客
http://dcr163.cn/106.html(转载时请注明本文出处及文章链接)