javascript - PHP电子表格不要下载excel文件
问题描述
我正在使用 php spreedsheet 处理 excel 文件,我试图提供一个包含数据的数组以在 excel 上下载。
我用ajax做这个请求。这是我的代码。我的代码在 symfony 3.4 上。我尝试使用标题,但是当我单击下载文件时,ajax 请求说好的,但不要给我 excel 文件
$datos = $request->request->get('datos');
$datos = json_decode($datos,true);
$cuenta = count($datos);
$spreadsheet = new Spreadsheet();
$cuentaColumnas = count($datos[0]);
$letra = "a";
$user = $this->getUser()->getUser();
for ($i=0; $i <$cuenta ; $i++) {
$numero = 1;
for ($j=0; $j < $cuentaColumnas ; $j++) {
$informacion = $datos[$i][$j];
$spreadsheet->getActiveSheet()->setCellValue($letra.$numero,$informacion);
$numero++;
}
$letra++;
}
// Set active sheet index to the first sheet, so Excel opens this as the first sheet
// create the writer
$writer = new Xlsx($spreadsheet);
$writer->save();
return $writer;
解决方案
实际上,您不能使用 Ajax 下载文件,当您使用 PHP 创建 excel 文件时,您是在服务器端创建它,您必须要求服务器下载它。因此,如果您想下载它,您可以做一个小技巧,使用您刚刚使用 PHP 创建的文件的 URL 创建一个隐藏的锚链接,并在 ajax 返回成功时单击它。
这是一个锚链接的例子,把它放在html视图上。
<a href="replace_src_of_the_file" download id="hiddenDonwloader" hidden></a>
这是 Ajax 的一个示例。当您达到“成功”意味着文件已成功创建时,您可以确保下载它。如果您之前不知道文件名,那么您也可以返回文件名并在“成功”中获取它并在单击之前更改href属性。
$.ajax({
headers: {
// Put your headers here
_your_header_
},
url: url_of_php, // put your url here
type: 'POST',
dataType: 'text',
data: {
datos: data // put your data to send here
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR, textStatus, errorThrown);
},
success: function (data) {
//Here we click the anchor link be sure that the href attribute is right
document.getElementById('hiddenDonwloader').click();
},
});
希望有帮助!
推荐阅读
- python-3.x - 使用 selenium python 登录失败。但手动尝试时没有问题
- amazon-web-services - 是否可以为 Amplify Datastore 构建动态查询?
- vue.js - 我在 vuejs 中收到 Invalid end tag 错误
- matlab - 八度音阶中的 & 和 && 有什么区别?
- javascript - 未定义的值添加到数组
- javascript - 自动选择/设置 editorparams 值
- webpack - 带有 postTransformPublicPath 的文件加载器
- r - 如何在 IntelliJ (PyCharm) 中运行闪亮的应用程序
- r - renv 0.12.0 是从项目库中加载的,但是 renv 0.11.0 记录在 lockfile 中
- c++ - 类对象到字符串的隐式转换运算符