PHP:Excel无法打开文件,因为文件格式或文件扩展名无效 [英] PHP : Excel cannot open the file because the file format or file extension is not valid

查看:160
本文介绍了PHP:Excel无法打开文件,因为文件格式或文件扩展名无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When I try to openning a xls file which I downloading from my application, I have this error :

excel无法打开文件,因为文件格式或文件扩展名无效.确认文件未损坏,并且文件扩展名与文件格式匹配.

excel cannot open the file because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file.

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

this is my php code : at first, I upload the xls file :

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).我已经尝试过更改文件扩展名或进行修复,但无法正常工作

I'm using MS 2016 (PhpOffice\PhpSpreadsheet). I already tried to change the file extension or to repar it but its not worked

推荐答案

感谢@Danny Battison当我使用Notpad打开文件时,在文件顶部看到空白,因此我添加了 ob_end_clean()(

Thanks @Danny Battison When I opened the file with Notpad I saw blanks on the top of the file, so I added ob_end_clean() (doc) just before :

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

而且效果很好.

这篇关于PHP:Excel无法打开文件,因为文件格式或文件扩展名无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆