简体   繁体   English

如何使用PHP为现有Excel提供下载?

[英]How do I provide a download for existing Excel with PHP?

I have a generated xls file on my server that I would like to push to the client for download but can't seem to get it working. 我的服务器上有一个生成的xls文件,我想将其推送到客户端进行下载,但似乎无法正常运行。 Here is what I have so far: 这是我到目前为止的内容:

$xlsFile = 'test.xls';

header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");;
header("Content-Disposition: attachment;filename=$xlsFile"); 
header("Content-Transfer-Encoding: binary ");  
exit();

My excel file is correct and can be opened if I open it from the server but how can I push this file to the client for download? 我的excel文件是正确的,如果从服务器打开它可以打开,但是如何将其推送到客户端进行下载?

You seem to be overdoing it with your "Content-type" headers. 您似乎用“ Content-type”标头来代替它。 Oh, and you need to actually send the file before exit() ing. 哦,您实际上需要在exit()之前发送文件。 All you need is 所有你需要的是

header("Content-Type: application/vnd.ms-excel");
header('Content-Disposition: attachment; filename="' . $xlsFile . '"');
readfile($xlsFile);
exit();

See this older post on the correct MIME type to send with your upload: 有关正确的MIME类型,请参阅此较早的帖子,以与您的上载一起发送:

Setting mime type for excel document 为Excel文档设置MIME类型

You just need to add one more line 您只需要再增加一行

$xlsFile = 'test.xls';

header("Content-Type: application/vnd.ms-excelapplication/vnd.ms-excel");
header("Content-Disposition: attachment;filename='$xlsFile'"); 
header("Content-Transfer-Encoding: binary ");  
echo file_get_contents($xlsFile);
exit();

Sample function. 示例功能。

function file_download($filename, $mimetype='application/octet-stream') {
  if (file_exists($filename)) {
// send headers
    header($_SERVER["SERVER_PROTOCOL"] . ' 200 OK');
// type
    header('Content-Type: ' . $mimetype);
// date of modified       
    header('Last-Modified: ' . gmdate('r', filemtime($filename)));
    header('ETag: ' . sprintf('%x-%x-%x', fileinode($filename), filesize($filename), filemtime($filename)));
// file size
    header('Content-Length: ' . (filesize($filename)));
    header('Connection: close');
    header('Content-Disposition: attachment; filename="' . basename($filename) . '";');
// send file
    echo file_get_contents($filename);
  } else {
    header($_SERVER["SERVER_PROTOCOL"] . ' 404 Not Found');
    header('Status: 404 Not Found');
  }
  exit;
}

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

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