Excel 文件无法通过浏览器自动下载

问题描述 投票:0回答:1

基本上,我在 Wordpress 中编码,创建了一个仅显示 Hello World 并在浏览器上自动下载的功能,但似乎不起作用?

内部:Functions.php

    wp_enqueue_script('llc-quote-profile-autocomplete', get_template_directory_uri() . '/llc-quote-profile-autocomplete.js', array('jquery', 'jquery-ui-autocomplete'), null, true);
    wp_localize_script('llc-quote-profile-autocomplete', 'llcQuoteAutocomplete', array(
        'ajaxurl' => admin_url('admin-ajax.php'),
        'nonce'   => wp_create_nonce('llc_quote_profile_autocomplete_nonce'),
    ));

require_once(ABSPATH . 'vendor/autoload.php');
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

function export_data_to_excel() {
    $spreadsheet = new PhpOffice\PhpSpreadsheet\Spreadsheet();
    $activeWorksheet = $spreadsheet->getActiveSheet();

    $activeWorksheet->setCellValue('A1', 'Hello World !');

    $writer = new PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);

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

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

    exit;
}
add_action('wp_ajax_export_data_to_excel', 'export_data_to_excel');
add_action('wp_ajax_nopriv_export_data_to_excel', 'export_data_to_excel');

自定义 Javascript.js 内部


    $('#llc-quote-details').on('click', '#exportExcelAndPDF', function() {
        var customersPo = $('#edited-customers-po').val();

        $.ajax({
            url: llcQuoteAutocomplete.ajaxurl,
            type: 'POST',
            data: {
                action: 'export_data_to_excel',
                customers_po: customersPo,
                nonce: llcQuoteAutocomplete.nonce,
            },
            success: function(response) {

            },
            error: function(xhr, status, error) {
                console.error(error); // Log any AJAX errors for debugging
            }
        });
    });

我只是首先通过 Hello World 进行测试,因为如果这有效,我现在就可以导出任何数据。

嗯。

  1. 设置标头以允许它
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment; filename="hello_world.xlsx"');
    header('Cache-Control: max-age=0');
  1. 尝试了 Google Chrome、MS Edge、Mozilla Firefox 但仍然无法下载。
javascript php wordpress download phpspreadsheet
1个回答
0
投票

这是Chrome引擎和Firefox引擎的一项安全功能。如果文件已准备好自动下载,您可以使用 jQuery 单击链接。

$( document ).ready(function() {
    $('#SELECTOR FOR FILELINK').click();
});
© www.soinside.com 2019 - 2024. All rights reserved.