PHP xlsx标头

时间:2012-04-17 20:21:17

标签: php header xlsx

这样可行:

myphpfile.php:

<?php
header('Content-disposition: attachment; filename=myfile.pdf');
header('Content-type: application/pdf');
readfile('myfile.pdf');
?> 

这里调用了php文件,PDF下载工作正常:

<a class = "oglasavanje" href = "../../cjenik/myphpfile.php">download</a><br/>

但这不起作用:

<?php
header('Content-disposition: attachment; filename=myfile.xlsx');
header('Content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
readfile('myfile.xlsx');
?>

.pdf和.xlsx文件都在同一个文件夹中。当我点击“下载”链接弹出下载窗口时,我保存文件,但无法打开该文件。它给了我以下错误:

  

Excel无法打开文件'myfile.xlsx',因为文件格式或   文件扩展名无效。验证文件尚未存在   已损坏且文件扩展名与文件格式匹配。

当我手动打开文件时(即不通过链接下载),文件打开正常

我正在使用WAMP,如果这很重要的话。

感谢任何帮助。

---编辑---

我在php.net上找到了这段代码:

ob_clean();
flush();

所以最终的代码看起来像这样,它可以工作:

$file = "myfile.xlsx";
header('Content-disposition: attachment; filename='.$file);
header('Content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Length: ' . filesize($file));
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate');
header('Pragma: public');
ob_clean();
flush(); 
readfile($file);

感谢大家的回答。

4 个答案:

答案 0 :(得分:7)

取决于您的浏览器,许多内容都可能导致Content-lengthCache-Control等行为

同时更改

Content-typeContent-Type

Content-dispositionContent-Disposition

尝试

$file = "myfile.xlsx" ;
header('Content-Disposition: attachment; filename=' . $file );
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Length: ' . filesize($file));
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate');
header('Pragma: public');
readfile('myfile.xlsx');

答案 1 :(得分:1)

根据您的网络浏览器,文件名可能无法完全保存期间。如果文件名不完整,您可以尝试替换此标题:

header('Content-disposition: attachment; filename=myfile.xlsx');

$filename = "myfile.xlsx";
header('Content-Disposition: attachment; filename="' . $filename . '"');

答案 2 :(得分:1)

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save($filename);
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Length: ' . filesize($filename));
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate');
header('Pragma: public');
readfile($filename);
return;

此解决方案适用于我,但当我尝试打开下载的文件时,我收到错误。对于.pdf文件只是空的。

答案 3 :(得分:0)

$file = "abc.xls";

header('Content-Description: File Transfer');
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);