简体   繁体   English

使用php下载excel文件后,它给出了错误

[英]After downloading the excel file using php it is giving error

I have made a file downloader here i am downloading the excel file it downloads successfully but when i open the file it gives me the error mention below Excel cannot open the file because the file format or file extension is not valid what is worng going on here 我已经在这里下载了一个文件下载程序我正在下载成功下载的excel文件但是当我打开文件时它给了我错误提到下面Excel无法打开文件因为文件格式或文件扩展名无效这里有什么问题

<?php

   if (isset($_POST['file_name'])) {

      $file_name = $_POST['file_name'];

      header('Content-type: application/octet-stream');
      header('Content-Disposition: attachment; filename="'.$file_name.'"');
     readfile('mystery_folder/'.$file_name);
    exit();
  }

 ?>

<form action="indexa.php" method="post" name="downloadform">

 <input name="file_name" value="My Tracker.xlsx" size="50" type="text">
<input type="submit" value="Download">

</form>

It's not a good idea to use a space in the filename: 在文件名中使用空格不是一个好主意:

value="My Tracker.xlsx"

It's probably not actually downloading the file, for lack of being able to find it. 它可能实际上并没有下载文件,因为它无法找到它。 You should rename the file without the space. 您应该重命名没有空格的文件。

Try to change Content-type: 尝试更改内容类型:

application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

and add: 并添加:

header('Content-Transfer-Encoding: binary');

This sample worked for me: 这个样本对我有用:

$file = 'sample.xlsx';
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
readfile(sprintf('./%s', $file));

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

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