PHP导出Excel文件有两种方式.第一种是引入PHPExcel的文件类,利用这个去导出文件,第二种不用引入文件,只利用PHP自身的特性即可导出文件来.第二种方式,简便快捷,但是有的地方兼容性不是很好,不如第一种.
public function file_out()
{
//$merchant为已经给数据库查询好的要导出的文件主体,这里做简化显示
$merchant = Db::name('merchant')->select();
$header = array('ID','商家名称','总收款金额','总交易笔数','总毛利','商家卡类型','商家优惠券类型');
$index = array('id','name','behind_preferrence','nums','gross_margin','type','card_type');
$filename = "XXXXXX商户表";
$this->file_excel($merchant,$filename,$header,$index);
}
//封装的文件导出函数
public function file_excel($list,$filename,$header,$index)
{
header("Content-type:application/vnd.ms-excel");
header("Content-Disposition:filename=".$filename.".xls");
$teble_header = implode("\t",$header);
$strexport = $teble_header."\r";
foreach ($list as $row){
foreach($index as $val){
$strexport.=$row[$val]."\t";
}
$strexport.="\r";
}
$strexport=iconv('UTF-8',"GB2312//IGNORE",$strexport);
exit($strexport);
}
利用header函数的特性,即可把数据塞进数据流,进行导出即可.
另外一个问题,因为是常会遇到的,在这里解决一下
很多的时候,导出适合搜索放在一起的,搜索走的是form表单提交的方式,但是导入按钮就不能写在form表单里面了.
文件导出是数据流的形式,不能用Ajax方式,$.post和$.get也不行,只能用form表单或者a标签的方式,
这里用a标签的方式,给a标签绑定上参数
<script>
layui.use('form',function(){
var form = layui.form;
var laydate = layui.laydate;
$('#file_out').click(function(){
var time_start = $('#time_start').val();
var time_end = $('#time_end').val();
var from_type = $('#from_type').val();
var id = $('#id').val();
console.log(time_start)
console.log(time_end)
console.log(from_type)
console.log(id)
// return false;
window.location = "/index.php/admin/merchant/file_out1?time_start="+time_start+"&time_end="+time_end+"&from_type="+from_type+"&id="+id;
});
});
</script>
另外url的写法,不能用tp自带的url函数
需要去拼接字符串,把参数拼接上去才行.