Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/excel/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP:Excel无法打开文件,因为文件格式或文件扩展名无效_Php_Excel_Phpspreadsheet - Fatal编程技术网

PHP:Excel无法打开文件,因为文件格式或文件扩展名无效

PHP:Excel无法打开文件,因为文件格式或文件扩展名无效,php,excel,phpspreadsheet,Php,Excel,Phpspreadsheet,当我试图打开从应用程序下载的xls文件时,出现以下错误: excel无法打开文件,因为文件格式或文件扩展名无效。 验证文件是否已损坏,以及文件扩展名是否与文件格式匹配 这是我的php代码: 首先,我上传xls文件: if (is_uploaded_file($_FILES["file_name"]["tmp_name"])) { if (rename($_FILES["file_name"]["tmp_name"], $directoryDestination.$nameDestinati

当我试图打开从应用程序下载的xls文件时,出现以下错误:

excel无法打开文件,因为文件格式或文件扩展名无效。 验证文件是否已损坏,以及文件扩展名是否与文件格式匹配

这是我的php代码: 首先,我上传xls文件:

if (is_uploaded_file($_FILES["file_name"]["tmp_name"])) {
   if (rename($_FILES["file_name"]["tmp_name"], $directoryDestination.$nameDestination))        {
      import::importFile($link,$directoryDestination.$nameDestination, $importLib, $excelName,$enddate);
    $_SESSION['message'] = "ok";
}else{
    $_SESSION['erreur'] = "Error";
}
然后在我的功能中:

use PhpOffice\PhpSpreadsheet\IOFactory;

importFile($link,$filename, $importLib, $excelName,$enddate){
header('Content-Type: text/html; charset=utf-8');
    // loading Excel file
    $objPHPExcel = IOFactory::load($filename);
    ....
    database 
    ....
    // copy the file
    mkdir($new_path,0777);
    chmod($new_path, 0777);
    copy($filename,$new_path.$excelName);
    unlink($filename);

// then , in other file, I try to download the file
$contents = file_get_contents($filepath);
$mime = mime_content_type($filepath);
$size = filesize($filepath);
$parts = explode("/", $file);
$filename = end($parts);

header("Content-Type: {$mime}");
header("Content-disposition: attachment; filename=\"" . basename($filename) . "\"");
header("Content-Length: {$size}");
print($contents);
exit();
我正在使用MS 2016(PhpOffice\PhpSpreadsheet)。 我已经尝试更改文件扩展名或重新编写,但没有成功

谢谢@Danny Battison 当我用Notpad打开文件时,我看到文件顶部有空格,所以我在前面添加了
ob\u end\u clean()
():

ob_end_clean();
header("Content-Type: {$mime}");

它工作正常。

在获取文件内容之前取消链接,这样文件就不存在了。尝试在记事本中打开该文件-它的格式可能不正确,并且很可能有异常消息。我在复制后删除该文件,因此它始终存在。当我尝试用记事本打开文件时,它的格式不正确,但我没有发现异常消息。使用ob函数处理类似的东西可能有点不太正常。在关闭PHP标记后的末尾检查PHP文件是否有新行(如果有,请去掉关闭PHP标记!)