【问题标题】:PHP : Excel cannot open the file because the file format or file extension is not validPHP:Excel 无法打开文件,因为文件格式或文件扩展名无效
【发布时间】:2020-07-11 10:34:00
【问题描述】:

当我尝试打开从应用程序下载的 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)。 我已经尝试更改文件扩展名或修复它,但它不起作用

【问题讨论】:

  • 您在 file_get_contents 之前取消链接,因此该文件将不存在。尝试在记事本中打开文件 - 它会出现格式错误,并且很可能会出现异常消息。
  • 复制后我删除了文件,所以它一直存在。当我尝试用记事本打开文件时,它的格式不正确,但我没有发现异常消息

标签: php excel phpspreadsheet


【解决方案1】:

感谢@Danny Battison 当我用 Notpad 打开文件时,我看到文件顶部有空白,所以我在之前添加了ob_end_clean() (doc):

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

而且效果很好。

【讨论】:

  • 对这样的事情使用 ob 函数可能有点 hacky。在关闭 php 标记后检查您的 PHP 文件末尾是否有新行(如果是,请删除关闭 php 标记!)
猜你喜欢
  • 2012-12-24
  • 1970-01-01
  • 1970-01-01
  • 2022-06-30
  • 2023-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多