目标:使用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

最新文章

  1. 详解Linux命令行下常用svn命令
  2. c# 筛选进程命令行,得其ProcessId(唯一标示符,简称pid),再通过pid结束进程
  3. linux(centos6)搭建ftp服务器
  4. c++ string 结束符‘\000’
  5. 解决VS2010中产生的ipch文件夹和sdf文件
  6. jquery get checkbox inside element(td).
  7. hdu2317Nasty Hacks
  8. poj3694(动态询问割桥的数目)
  9. 连载:面向对象的葵花宝典:思考、技巧与实践(39) - 设计原则 vs 设计模式
  10. jQuery获取Select选择的Text和 Value(转,待测试确认)
  11. python requests库学习笔记(上)
  12. 听翁恺老师mooc笔记(13)--类型定义和联合
  13. slitaz的root密码
  14. [精华][推荐]CAS SSO单点登录服务端客户端实例
  15. SQL语句在数据库中可以执行在mybatis执行不了
  16. jar与war包区别,转自https://www.jianshu.com/p/3b5c45e8e5bd
  17. 主机性能监控之wmi 获取进程信息
  18. poj3126
  19. python SMTP
  20. Spring Batch 远程分区和远程分块的区别

热门文章

  1. patch的用法【转】
  2. SQL Server 变量定义
  3. Tomcat 配置虚拟目录以及虚拟主机
  4. MySQL之表关系
  5. 第07组 Beta冲刺(2/4)
  6. python的安装与配置
  7. IDEA一个工程如何启动多次
  8. Windows 下升级 node &amp; npm 到最新版本
  9. SQL学习-SQL Server
  10. Linux安装centos