php ajax生成excel并下载

目标:使用php,通过ajax请求的方式生成一个excel,然后下载。

思路:大致思路是发送一个ajax请求到后台,后台php处理后生成一个excel文件,然后把生成的文件放到一个临时目录,然后把文件链接返回给前端。前端接受到后,然后通过给定的地址,去下载该文件....

代码实现:

前端部分:

<pre name="code" class="html">function outExcel(){
var allSelect = $('._newId:checked').length;
if(allSelect == 0){
layer.msg('请选择需要导出的记录');
return false;
}
var ids = [];
$('._newId:checked').each(function(){
ids.push($(this).val());
});
var params = {id:ids};
$.post("{:U('Home/Saidi/outExcel')}",params,function(res){
if(res.status){
window.location.href = ("{:U('Home/Saidi/download')}?file="+res.url+'&token='+res.token);
}else{
layer.msg('系统错误,操作失败');
}
},'json');
}


其中token是用来做安全校验的.....
后台部分:

使用的是PHPExcel插件。这里用的是TP框架

public function outExcel(){
$ids = I('post.id','','trim');
if(empty($ids)){
exit(json_encode(array('status'=>false,'url'=>'','token'=>'')));
}
$where['id'] = array('in',$ids);
$data = M('news','xyl_')->where($where)->select();
if(!empty($data)){
Vendor('PHPExcel.PHPExcel');
Vendor('PHPExcel.PHPExcel.IOFactory');
$phpExcel = new PHPExcel();
$phpExcel->setActiveSheetIndex(0)
->setCellValue('A1', '序号')
->setCellValue('B1', '新闻标题')
->setCellValue('C1', '新闻摘要')
->setCellValue('D1', '新闻内容')
->setCellValue('E1', '新闻来源')
->setCellValue('F1', '作者')
->setCellValue('G1', '来源网址');
$len = count($data);
for($i = 0 ; $i < $len ; $i++){
$v = $data[$i];
$rownum = $i+2;
$phpExcel->getActiveSheet()->setCellValue('A' . $rownum, $i);
$phpExcel->getActiveSheet()->setCellValue('B' . $rownum, $v['title']);
$phpExcel->getActiveSheet()->setCellValue('C' . $rownum, $v['summary']);
$phpExcel->getActiveSheet()->setCellValue('D' . $rownum, $v['content']);
$phpExcel->getActiveSheet()->setCellValue('E' . $rownum, $v['from']);
$phpExcel->getActiveSheet()->setCellValue('F' . $rownum, $v['author']);
$phpExcel->getActiveSheet()->setCellValue('G' . $rownum, $v['url']);
}
$phpExcel->setActiveSheetIndex(0);
$filename=date('YmdHis').'.xlsx';
$objWriter=PHPExcel_IOFactory::createWriter($phpExcel,'Excel2007');
$filePath = C('TMP_PATH').$filename;
$objWriter->save($filePath);
if(!file_exists($filePath)){
$response = array(
'status' => false,
'url' => '',
'token'=>''
);
}else{
$response = array(
'status' => true,
'url' => $filename,
'token'=>$this->getDownLoadToken($filename)
);
}
}else{
$response = array(
'status' => false,
'url' => '',
'token'=>''
);
}
exit(json_encode($response));
}
private function getDownLoadToken($filename,$length = 10){
$str = null;
$strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
$max = strlen($strPol)-1;

for($i=0;$i<$length;$i++){
$str.=$strPol[rand(0,$max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数
}
$res = md5($str.time());
S($res,$filename);
return $res;
}
public function download(){
$fileName = I('get.file','','trim');
$token = I('get.token','','trim');
if(empty($token) || !S($token)){
header("HTTP/1.0 404 Not Found");
exit;
}
$path = C('TMP_PATH').$fileName;
if(!file_exists($path)){
header("HTTP/1.0 404 Not Found");
exit;
}else{
$file = @fopen($path,"r");
if(!$file){
header("HTTP/1.0 505 Internal server error");
exit;
}
header("Content-type: application/octet-stream");
header("Accept-Ranges: bytes");
header("Accept-Length: ".filesize($path));
header("Content-Disposition: attachment; filename=" . $fileName);
while(!feof($file)){
echo fread($file,2048);
}
fclose($file);
@unlink($path);
S($token,NULL);
exit();
}
}


getDownLoadToken这个方法是用来获取凭证的,也就是token


原文:https://blog.csdn.net/wangyibo5843/article/details/53116717

原文地址:https://www.cnblogs.com/showcase/p/10898560.html