为了账号安全,请及时绑定邮箱和手机立即绑定

PHP电子表格不要下载excel文件

PHP电子表格不要下载excel文件

PHP
守候你守候我 2022-01-08 20:15:07
我正在使用 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;
查看完整描述

1 回答

?
FFIVE

TA贡献1797条经验 获得超6个赞

实际上,您不能使用 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();

},

});

希望有帮助!


查看完整回答
反对 回复 2022-01-08
  • 1 回答
  • 0 关注
  • 188 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号