【问题标题】:export table data to php using ajax使用ajax将表数据导出到php
【发布时间】:2023-04-04 19:07:01
【问题描述】:

我正在编写 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/ 文件被下载

【问题讨论】:

    标签: php jquery ajax drupal-8


    【解决方案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;
    }
    ?>
    

    【讨论】:

    • 以上是csv,我期待excel导出
    • 这适用于您拥有的任何类型的文件。我将为 xls 编辑我的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-09
    • 2014-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-22
    相关资源
    最近更新 更多