javascript - 使用 php 中的 spout 库导出 excel 时文件扩展名或文件无效

标签 javascript php phpexcel-1.8.0 spout

我在使用 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 cannot open the file 'person2018-09-19-07-20-30.xlsx' 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

enter image description here

最佳答案

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

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

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

关于javascript - 使用 php 中的 spout 库导出 excel 时文件扩展名或文件无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52399085/

相关文章:

javascript - PHP 在 javascript 中用于下拉菜单

javascript - 获取多维数组N个元素的所有组合

javascript - 纯 Javascript mouseenter 和 mouseleave 事件委托(delegate)与 React 问题

php - 深入 MYSQL 和闭包表树

php - 对 MySQL 的查询返回 null,之前它工作得很好

PHPExcel 将 48 行中的 38 行从 xlsx 文件插入 MySQL

php - 如何验证PHPExcel生成的 ".xls"文件中的密码?

php - 如何在php电子表格图表中设置数据标签的位置

javascript - AngularJs 是空列表

javascript - 在另一个 promise 中解决 promise