使用ajax调用下载PHPExcel [英] PHPExcel download using ajax call

查看:59
本文介绍了使用ajax调用下载PHPExcel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

App::import('Vendor', 'PHPExcel/Classes/PHPExcel');
$objPHPExcel = new PHPExcel();
$objPHPExcel->getActiveSheet()->setTitle('ReceivedMessages');
header('Content-Type: application/vnd.ms-excel');
$file_name = "kpi_form_".date("Y-m-d_H:i:s").".xls";
header("Content-Disposition: attachment; filename=$file_name");
// If you're serving to IE 9, then the following may be needed
header('Cache-Control: max-age=1');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');

当我直接从浏览器中调用上述代码时,将下载结果文件.但是,如果我对上述代码进行ajax调用,则不会得到下载提示.我可以从控制台选项卡中看到ajax调用已成功完成,并且在响应数据中看到了一堆随机字符.我假设这是excel对象.

When I call above code directly from the browser, the result file is downloaded. But if I make an ajax call to above code, I don't get the download prompt. I can see from console tab that the ajax call was successfully completed and a bunch of random characters is seen in the response data. I'm assuming that is the excel object.

有人知道我如何使用Ajax实现下载excel功能吗?我不想刷新页面.当用户单击导出"按钮时,应该对php文件进行ajax调用,并提示用户进行下载.

Does anyone know how I can achieve the download excel feature using ajax? I don't want to refresh the page. When the user clicks on the "export" button, there should be an ajax call to the php file and prompt the user to download.

推荐答案

在目标ajax成功函数中添加target = _blank,如下所示

add target=_blank in your ajax success function like below

success: function(){
  window.open('http://YOUR_URL','_blank' );
},

否则,您可以通过jQuery触发功能或类似功能巧妙地处理以在新标签中打开Excel下载链接.

otherwise you can handle smartly to open your Excel download link in new tab with jQuery trigger function or etc.

这篇关于使用ajax调用下载PHPExcel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆