话不多说上干活
public function downloadMatchDataAction()
{
// 要下载的信息
$user = new UserModel();
$sql = "SELECT id,name,age,sex ORDER BY age DESC LIMIT 0,100";
$list = $user->query($sql);//这里可以理解为查出来的二维数组
$th = ['编号','姓名','年龄','性别'];
$datas = array();//定义空数组,用来装自己想要的数据格式
foreach($list as $key => $val){
$datas[$key][] = $val["id"];
$datas[$key][] = $val["name"];
$datas[$key][] = $val["age"];
$datas[$key][] = $val["sex"];
}
//解释一下这个循环,$datas为二维数组,$key为$list的键,将$list里面的键变为$datas里面的键最后再给这个键附上我刚才查询的值
$this->outCsvTableAction('match',$th,$datas);//这里注意,指的是调用累内该方法
exit;//我这里我选择了退出因为导出并下载我已经完成了,做完以后还需要做记录请自行修改。
}
/**
name你要导出的文件名" role="presentation" style="position: relative;">name你要导出的文件名th 表头表标题
datas重构后的数组∗∗/publicfunctionoutCsvTableAction(" role="presentation" style="position: relative;">datas重构后的数组∗∗/publicfunctionoutCsvTableAction(name, th," role="presentation" style="position: relative;">th,datas){
header(“Content-type:text/csv”);
header(“Content-Disposition:attachment;filename=” . date(‘Ymd’) . ‘_’.name.′.csv′);header(‘Cache−Control:must−revalidate,post−check=0,pre−check=0′);header(‘Expires:0′);header(‘Pragma:public′);" role="presentation" style="position: relative;">name.′.csv′);header(‘Cache−Control:must−revalidate,post−check=0,pre−check=0′);header(‘Expires:0′);header(‘Pragma:public′);str = ”;
foreach (thas" role="presentation" style="position: relative;">thasvalue) {
str.=iconv(′utf−8′,′gb2312′," role="presentation" style="position: relative;">str.=iconv(′utf−8′,′gb2312′,value).’,’;
//解释下这个函数 : iconv(输入的字符集,输出的字符集,要转换的字符串)
}
str=rtrim(" role="presentation" style="position: relative;">str=rtrim(str,’,’);
str.=“\n”;foreach(" role="presentation" style="position: relative;">str.=“\n”;foreach(datas as v)$str.=“\t”;foreach($vas$v1)$str.=iconv("utf−8","gb2312",$v1).′,′;$str=rtrim($str,′,′);$str.=“\n”;die(" role="presentation" style="position: relative;">v)$str.=“\t”;foreach($vas$v1)$str.=iconv("utf−8","gb2312",$v1).′,′;$str=rtrim($str,′,′);$str.=“\n”;die(str);
}
以上
文章来源: PHP将表格导出为EXCEL格式
发表评论