簡體   English   中英

無法通過創建的方式下載 PHP 中的 xlsx 文件

[英]Can't download xlsx file in PHP through it's created

在 public/js 文件中,我請求 $ajax,得到的響應只是字符串,而不是文件。

如果客戶端使用 ajax 發送請求,服務器將使用字符串而不是 xlsx 文件進行響應。

這是請求部分:

$("#downloadXLS").on('click', function () {
        $.ajax({
            type: 'get',
            url: appRoot + "transactions/downloadXLS/",

            success: function () {
            },

            error: function () {
            }
        });
    });

這是 php 響應 function:

public function downloadXLS()
  {
    // Filter the excel data 
    function filterData(&$str)
    {
      $str = preg_replace("/\t/", "\\t", $str);
      $str = preg_replace("/\r?\n/", "\\n", $str);
      if (strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
    }

    // Excel file name for download 
    $fileName = "transaction-data_" . date('Y-m-d') . ".xls";

    // Column names 
    $fields = array('No.',  'Pay Date',  'Company');

    // Display column names as first row 
    $excelData = implode("\t", array_values($fields)) . "\n";

    // Headers for download 
    header("Content-Type: application/vnd.ms-excel");
    header("Content-Disposition: attachment; filename=\"$fileName\"");

    $allTranscations = $this->transaction->getAll();
    if (is_array($allTranscations)) {
      // Output each row of the data 
      foreach ($allTranscations as $key => &$trans) {
        $lineData = array($key + 1, $trans->pay_time, $trans->company);
        array_walk($lineData, 'filterData');
        $excelData .= implode("\t", array_values($lineData)) . "\n";
      }
    } else {
      $excelData .= 'No records found...' . "\n";
    }

    // Render excel data 
    echo $excelData;

    exit();
  }

在此處輸入圖像描述

您無法通過 ajax 請求下載文件。 試試 location.href=transactions/downloadXLS。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM