简体   繁体   English

从服务器下载 Excel 文件已损坏 - PHP

[英]Download Excel File from Server has been corrupted - PHP

I have a problem about downloading Excel file from server.我在从服务器下载 Excel 文件时遇到问题。

the excel file was already saved on the server and I downloaded it using the code below. excel 文件已经保存在服务器上,我使用下面的代码下载了它。

if(file_exists($reportPath)){
    //content type
    header('Content-type: application/vnd.ms-excel');
    //open/save dialog box
    header('Content-Disposition: attachment; filename='.$dirFile[count($dirFile)-1]);
    //read from server and write to buffer
    readfile($reportPath);
}

But the downloaded file was corrupted.但是下载的文件已损坏。

I'm pretty sure that the file saved on the server is not corrupted since I have get it manually from the server to my local desktop.我很确定保存在服务器上的文件没有损坏,因为我已经从服务器手动将它获取到我的本地桌面。

Meaning, the data has been corrupted on the fly.意思是,数据已被即时损坏。

Please help, thank you, I'm using PHP请帮助,谢谢,我正在使用 PHP

这是下载后的文件

Can you try these headers?你能试试这些标题吗?

header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="'.$dirFile[count($dirFile)-1].'"');
header('Cache-Control: max-age=0');

And see if it's working... Cheers!看看它是否有效......干杯!

Download script should be separate file.下载脚本应该是单独的文件。 Actually you should not print out anything in this script实际上你不应该在这个脚本中打印出任何东西

//Add below to download the text file created
$filename = $file; //name of the file
$filepath = $file; //location of the file. I have put $file since your file is create on the same folder where this script is
header("Cache-control: private");
header("Content-type: application/force-download");
header("Content-transfer-encoding: binary\n");
header("Content-disposition: attachment; filename=\"$filename\"");
header("Content-Length: ".filesize($filepath));
readfile($filepath);
exit;
    $fileName = "data.xls";
    $object_writer = PHPExcel_IOFactory::createWriter($object, 'Excel5');
    ob_end_clean();
    header("Content-Type: application/download");
    header('Content-Disposition: attachment;filename=' . $fileName);
    $object_writer->save('php://output');

use ob_end_clean() to clear the output buffer.使用 ob_end_clean() 清除输出缓冲区。

This is what fixed my issue:这就是解决我的问题的原因:

  • adding ob_end_clean funct after the save.保存后添加ob_end_clean函数。
  • adding exit at the end of the script.在脚本末尾添加exit

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM