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;


守候你守候我
浏览 189回答 1
1回答

FFIVE

实际上,您不能使用 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&nbsp; _your_header_},url: url_of_php, // put your url heretype: 'POST',&nbsp;dataType: 'text',data: {&nbsp; datos: data // put your data to send here},error: function (jqXHR, textStatus, errorThrown) {&nbsp; console.log(jqXHR, textStatus, errorThrown);},success: function (data) {//Here we click the anchor link be sure that the href attribute is right&nbsp; document.getElementById('hiddenDonwloader').click();},});希望有帮助!
打开App,查看更多内容
随时随地看视频慕课网APP