我最近使用composer安装了PhpSpreadsheet,我使用的是php 7.4。
我正在尝试打开一个 Excel 文件,更改一些单元格值,然后保存这些更改的文件(下载到客户端)
经过一些研究并添加标头以接受 .xlsx 文件并使自动下载正常工作,这工作得很好,但只有一次。在不进行任何更改并在第二天运行相同的情况下,后台似乎没有发生任何事情。看起来 IOfactory::load 可以读取文件,但自动下载不再发生。
我尝试通过 javascript 将加载的 $spreadsheet 从客户端记录到控制台,并且可以看到sheetml 乱码。这告诉我加载器正在工作并且编写器正在工作,也许下载的标头是错误的,但与大量在线示例相比,我看不出它有什么问题。我很惊讶为什么它只能工作一次,现在我不确定问题出在哪里。
任何帮助弄清楚为什么这会起作用,然后停止工作而不改变任何东西的帮助将不胜感激。
excelCompleteExport.php:
require 'PHPSpreadsheet/vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load("NedbankBBCommTemplate_REMSYSTEM.xlsx");
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="result2.xlsx"');
set_error_handler (
function($errno, $errstr, $errfile, $errline) {
throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
}
);
try
{
\PhpOffice\PhpSpreadsheet\Shared\File::setUseUploadTempDirectory(true);
$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('php://output');
//echo "<script type='text/javascript'>console.log('done');</script>";
}
catch(Exception $e)
{
echo "<script type='text/javascript'>console.log('".$e->getMessage()."');</script>";
}
从 javascript 调用:
function ExpExcel()
{
$("#InvisElement").load("excelCompleteExport.php");
}
HTML 按钮调用 JavaScript 函数:
<button id="ExpExcel" style="width: 200px;" class="navbtn" type="submit" onclick="ExpExcel(); return false;">Export to Excel</button>
自动下载主要受浏览器限制(防止恶意软件下载)。您可以尝试通过链接/按钮上的 jQuery 在新选项卡中打开生成的 .xlsx 文件。
function ExpExcel()
{
$.ajax({
type: 'GET',
cache: false,
url: "excelCompleteExport.php",
xhrFields: {
// make sure the response knows we're expecting a binary type in
return.
// this is important, without it the excel file is marked corrupted.
responseType: 'arraybuffer'
}
})
.done(function (data, status, xmlHeaderRequest) {
var downloadLink = document.createElement('a');
var blob = new Blob([data],
{
type: xmlHeaderRequest.getResponseHeader('Content-Type')
});
var url = window.URL || window.webkitURL;
var downloadUrl = url.createObjectURL(blob);
var fileName = 'result.xlsx';
if (typeof window.navigator.msSaveBlob !== 'undefined') {
window.navigator.msSaveBlob(blob, fileName);
} else {
if (fileName) {
if (typeof downloadLink.download === 'undefined') {
window.location = downloadUrl;
} else {
downloadLink.href = downloadUrl;
downloadLink.download = fileName;
document.body.appendChild(downloadLink);
downloadLink.click();
}
} else {
window.location = downloadUrl;
}
setTimeout(function () {
url.revokeObjectURL(downloadUrl);
},
500);
}
});
}