使用ajax将表数据导出到php

时间:2019-06-05 16:36:23

标签: php jquery ajax drupal-8

我正在编写PHP代码(在drupal中),以便使用ajax将数据导出到excel文件中。我没有收到任何错误,但是当我单击按钮导出到excel时文件没有下载。 但是当我直接加热URL(从浏览器)时,文件就会下载

这是ajax代码

jQuery('.export-csv', context).once('export').click(function() {
console.log('test');

var role = 'teacher';

 /*get basepath*/
 var basepath = drupalSettings.path.baseUrl;
jQuery.ajax({
 type : 'GET',
url  : basepath + 'report-export/'+role,
    success : function (data) {
console.log('success');
},
error: function () {
console.log('error');
}
})
})

和控制器中的php函数下载Excel文件

 public function exportToExcel($role)
    {
        $filename = "report.xls";       
        header("Content-Type: application/vnd.ms-excel");
        header("Content-Disposition: attachment; filename=\"$filename\"");
        $records = array(
        '0' => array('Name'=> 'user1', 'Status' =>'complete', 'Priority'=>'Low', 'Salary'=>'001'),
        '1' => array('Name'=> 'user2', 'Status' =>'inprogress', 'Priority'=>'Low', 'Salary'=>'111'),
        '2' => array('Name'=> 'user3', 'Status' =>'hold', 'Priority'=>'Low', 'Salary'=>'333'),
        '3' => array('Name'=> 'user4', 'Status' =>'pending', 'Priority'=>'Low', 'Salary'=>'444'),
        '4' => array('Name'=> 'user5', 'Status' =>'pending', 'Priority'=>'Low', 'Salary'=>'777'),
        '5' => array('Name'=> 'user6', 'Status' =>'pending', 'Priority'=>'Low', 'Salary'=>'777')
        );

$heading = false;
    if(!empty($records))
      foreach($records as $row) {
        if(!$heading) {
          // display field/column names as a first row
          echo implode("\t", array_keys($row)) . "\n";
          $heading = true;
        }
        echo implode("\t", array_values($row)) . "\n";
      }
        exit;
    }

尽管我没有收到错误,但文件没有下载。并且在ajax控制台中也收到成功消息。当我直接点击网址为     site.com/report-export/文件已下载

1 个答案:

答案 0 :(得分:1)

您缺少几个标头标签来完成这项工作。这对我有效,程序风格。快速,轻松。

form.php

 <a class="btn btn-default" href="download.php">Download Excelsheet</a>

download.php

<?php
$file = '../path-to/filename.csv';//csv
$file = '../path-to/filename.xls';//excel

if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');//csv
    header("Content-Type: application/xls");//excel
    header('Content-Disposition: attachment; filename="'.basename($file).'"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    readfile($file);
    exit;
}
?>