前端:
点击导出触发click事件,传值export指令和args关键字(args是指我们是否有查询取哪些数据)到控制器
$(document).on("click", "#go-export", function () {
var args = "";
if($('#keyword').val() != ''){
args = args + '/keyword/'+$('#keyword').val();
}
window.open('index/export/1'+args);
});
控制器:
if(!empty($postData['keyword'])){
$map['project_name'] = array('like','%'.$postData['keyword'].'%');
}
$dataList = $goods->where($map)->select();
for ($i = 0; $i < sizeof($dataList); $i++) {
$result[$i]['id'] = $dataList[$i]['id'];
$result[$i]['合同号'] = $dataList[$i]['contract_number'];
$result[$i]['项目名称'] = $dataList[$i]['project_name'];
$result[$i]['销售月份'] = $dataList[$i]['sales_month'];
$result[$i]['房型'] = $dataList[$i]['room_type'];
$result[$i]['渠道'] = $dataList[$i]['channel'];
$result[$i]['售卖单价'] = $dataList[$i]['one_prices'];
$result[$i]['结算单价'] = $dataList[$i]['all_prices'];
$result[$i]['房间数量'] = $dataList[$i]['room_num'];
$result[$i]['减扣金额'] = $dataList[$i]['damount'];
$result[$i]['备注'] = $dataList[$i]['note'];
$result[$i]['更新日期'] = $dataList[$i]['update_time'];
}
$csv = "";
for($i=0;$i<sizeof($result);$i++){
if($i == 0){
$head = '"';
foreach($result[$i] as $key=>$value){
if($head != '"'){
$head .= '","';
}
$head .= $key;
}
$head .= "\"\n";
$csv .= $head;
}
$csv .= '"' . implode('","', $result[$i]) . '"' . "\n";
}
$this->export($csv);
}
下载控制器:ecport方法
public function export($res){
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=".date('YmdHis').".csv");
header("Content-Type: application/csv");
header("Content-Transfer-Encoding: binary");
print mb_convert_encoding($res,"GBK", "UTF-8");
//print iconv('UTF-8', 'GBK//IGNORE', $res);
}