首页 > 解决方案 > PhpSpreadsheet 强制下载文件不起作用 - 格式错误

问题描述

问题:创建的(XLSX)文件被发送到电子邮件并且运行良好,但是当我使用这个脚本下载它时它没有打开,MS Excel 显示“无效的文件格式或扩展名”错误。

我写了一个脚本来强制从服务器下载一个excel文件,如果有的话$_GET,如果没有的话,通过电子邮件发送。

$writer = new Xlsx( $spreadsheet );
$writer->save( 'file.xlsx' );
$file_path = PATH_TO_FILE; // for example purposes

if( isset( $_GET['action'] ) && 'download' == $_GET['action'] ) {
    // force download file
    if( file_exists( $file_path ) ) {
        header('Content-Description: File Transfer');
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment; filename=" ' . basename( $file_path ) . '"');
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize( $file_path ) );
        flush(); // Flush system output buffer
        readfile( $file_path );
        exit;
    }
}
else {
    // send email
    $to = 'example@example';
    $subject = 'subject';
    $body = 'body ' . date( 'd-m-Y' );
    $headers = array(
        'Content-Type: text/html; charset=UTF-8',
        'From: John Doe <info@example.com>',
    );
    $attachment = array( $file_path );

    $result = wp_mail( $to, $subject, $body, $headers, $attachment );
    if( !$result ) {
        error_log( '$result: ' . print_r( $result, true ) );
    }
}

*PATH_TO_FILE导致实际文件

知道为什么文件下载脚本会生成错误的 excel 文件吗?

谢谢!

标签: phpexcelspreadsheetphpspreadsheet

解决方案


感谢@ino 的提示,我设法解决了这个问题。

必须确保PHP 标记之前没有 HTML/CSS/JS。


推荐阅读