【问题标题】:File extension or file is not valid at the time export excel using spout library in php文件扩展名或文件在 php 中使用 spout 库导出 excel 时无效
【发布时间】:2018-09-19 05:59:08
【问题描述】:

我在使用 spout 库导出 excel 时遇到问题。我不知道我的代码中的问题在哪里。我对 spout 库知之甚少。我已经尝试了很多次,但同样的错误一次又一次地发生。请指导我问题出在哪里。

代码:

<?php 
include('php_script/db.php');
use Box\Spout\Common\Type;
use Box\Spout\Writer\Style\Border;
use Box\Spout\Writer\Style\BorderBuilder;
use Box\Spout\Writer\Style\Color;
use Box\Spout\Writer\Style\StyleBuilder;
use Box\Spout\Writer\WriterFactory;
include('php_script/spout/src/Spout/Autoloader/autoload.php');  
$sql = mysqli_query($con,"select * from person ");
$border = (new BorderBuilder())
        ->setBorderBottom(Color::GREEN, Border::WIDTH_THIN, Border::STYLE_DASHED)
        //->setFontColor(Color::BLUE)
        //->setBackgroundColor(Color::YELLOW)
        ->build();
    $style = (new StyleBuilder())
        ->setBorder($border)
        ->build();
    $filePath = "person".date("Y-m-d-H-i-s").'.xlsx';
    $writer = WriterFactory::create(Type::XLSX);
    $writer->openToFile($filePath);

    $array = ['TYPE'];
    
    $writer->addRowWithStyle($array, $style);

    
   
    while( $rows = mysqli_fetch_assoc($sql)) {
   
    $Type_subsidiary = $rows['Type_subsidiary'];
    $data =  [$Type_subsidiary];
    $writer->addRow($data);
    }

    $writer->close();
     if (file_exists($filePath)) {
            header('Content-Description: File Transfer');
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename="'.basename($filePath).'"');
            header('Expires: 0');
            header('Cache-Control: must-revalidate');
            header('Pragma: public');
            header('Content-Length: ' . filesize($filePath));
            readfile($filePath);
            exit;
        }


?>

错误:

Excel 无法打开文件“person2018-09-19-07-20-30.xlsx”,因为文件格式或文件扩展名无效。验证文件没有损坏并且文件扩展名与文件格式匹配

【问题讨论】:

  • 尝试将 XLSX 更改为 XLS。 xlsx 文件基本上是一个 zip 文件,其中包含多个文件以帮助构建文件。
  • 我已将 XLSX 更改为 XLS。 $filePath = "person".date("Y-m-d-H-i-s").'.xls';但不起作用。 :(
  • 代码图片和不遵循 MVCE 标准 (stackoverflow.com/help/mcve) 在堆栈上是错误的形式,不会回答您的问题。
  • 这么说,你可以直接访问创建的文件吗?它应该被保存。
  • 文件保存在同一目录中。

标签: javascript php phpexcel-1.8.0 spout


【解决方案1】:

您是否尝试过让 spout 创建文件并将其直接“发送”到浏览器而不指定其文档 http://opensource.box.com/spout/getting-started/ 中指定的标题?

$writer->openToBrowser($fileName); // stream data directly to the browser

希望这会有所帮助,在我们的应用程序(基于 Symfony)中,我们使用 spout 但无需指定标头和文件路径。

【讨论】:

  • 我试过 $writer->openToBrowser($fileName);这适用于本地服务器,但不适用于实时服务器。
  • 正如亚历克斯所问的,您是否可以直接在实时服务器上打开创建的文件?不是通过浏览器,而是通过命令行、ftp 或任何你习惯的方式。这将有助于了解错误是来自文件创建还是“发送”到浏览器。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-06-30
  • 2020-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-06
相关资源
最近更新 更多