无法下载 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 响应函数:
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.
在 public/js 文件中,我请求 $ajax,得到的响应只是字符串,而不是文件。
如果客户端使用 ajax 发送请求,服务器将使用字符串而不是 xlsx 文件进行响应。
这是请求部分:
$("#downloadXLS").on('click', function () {
$.ajax({
type: 'get',
url: appRoot + "transactions/downloadXLS/",
success: function () {
},
error: function () {
}
});
});
这里是 php 响应函数:
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.