如何强制下载 PHP 中的 .xlsx 文件而不损坏它?

How force download an .xlsx file in PHP without having it corrupted?

None 个已经存在的问题帮助了我。 我正在尝试强制下载文件类型为 .xlsx 的 excel 文件。它在这样的下载代码中工作得很好:

echo "<a href='" . $dateiname . "'>Datei herunterladen</a>";

但是每当我尝试进行强制下载时,它都不起作用。我尝试了关于 Whosebug 的各种问题的各种 headers,最后两个是

header('Content-type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $dateiname . '"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Pragma: no-cache');
header('Content-Length: ' . filesize($dateiname));
$objWriter->save('php://output');

header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
header("Content-Transfer-Encoding: binary ");
header('Content-Disposition: attachment; filename='.basename($dateiname));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($dateiname));
$objWriter->save('php://output');

我在创建文件的同一个文件中尝试过,但也在一个单独的文件中尝试过,但无论哪种方式,我总是得到错误:

Excel cannot open the file (filename) because the file format or file extension is not valid. Verify that the file has not been corruted and that the file extension matches the format of the file.

我服务器上的文件本身看起来非常好。

我找到了如何使用 PHPExcel 强制下载 xls 文件。

header("Content-Disposition: attachment; filename={$fileName}.{$fileFormat}");
header("Content-Type: application/vnd.ms-excel;");
header("Cache-Control: max-age=0");

$objWriter->save('php://output');

希望对您有所帮助。