错误:文件格式或文件扩展名无效。验证文件未损坏

时间:2019-04-03 05:59:59

标签: php phpspreadsheet

我想在我的项目中使用PHPSpreadsheet库将数据导出到excel文件,但是当我尝试打开文件时,此错误显示:excel无法打开文件,因为文件格式或文件扩展名无效。确认文件未损坏

  • 注意:我在项目中使用MVC 因此控制器中的代码如下:

           protected function Excel($view, $variables = [])
    {
      require_once PATH_LIBRARY_FOLDER.'PhpSpreadsheet\vendor\autoload.php';
      ob_start();
      // Note: make new Spreadsheet object
      $spreadsheet = new Spreadsheet();
      // Note: get current active sheet (frist sheet)
      $sheet = $spreadsheet->getActiveSheet();
      $sheet->setCellValue('A1', 'Hello World !');
    
      extract($variables);
      include($this->viewPath.$view.'.php');
      // Note: set the header to define it is excel file
      header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
      // Note: set the header to define excel file name
      header("Content-Disposition: attachment;filename=\"filename.xlsx\"");
      header("Cache-Control: max-age=0");
    
      // Note: create IOFactory object
      $writer = IOFactory::createWriter($spreadsheet, 'xlsx');
      ob_get_clean();
    
      $writer->save('php:://output');
      exit();
    }
    

当我以文本形式打开文件时,发现此错误:

  

致命错误:未捕获的PhpOffice \ PhpSpreadsheet \ Writer \ Exception:无法打开php :: //输出以进行编写。在C:\ xampp \ htdocs \ GL_App \ Library \ PhpSpreadsheet \ vendor \ phpoffice \ phpspreadsheet \ src \ PhpSpreadsheet \ Writer \ Xlsx.php:218

2 个答案:

答案 0 :(得分:0)

更改此代码行

$writer->save('php:://output');

$writer->save('php://output');

应该可以。另外,如何将数据传递到Excel工作表?您的数据可能已损坏。

请在autoload.php之后将其插入您的代码中

    use PhpOffice\PhpSpreadsheet\Spreadsheet;
    use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

答案 1 :(得分:0)

我有同样的问题,我的解决方案在这里。只需将代码放在下面:

ob_end_clean();

代码:

        ob_end_clean();
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="'. $filename );
        header('Cache-Control: max-age=0');

        $writer->save('php://output'); // download file