shuchkin / simplexlsxgen

Export data to Excel. PHP XLSX generator
MIT License
1k stars 201 forks source link

download excel in wordpress ajax #154

Open persianlionn opened 2 months ago

persianlionn commented 2 months ago

Hi I use this plugin in wordpress theme. Everything works fine. But I don't know how to download the file in Ajax.

    $(document).on('click', '#export_to_excel', function (e) {
        e.preventDefault();
        $.ajax({
            url: ajax_url,
            type: 'post',
            cache: false,
            data: {action:'export_to_excel'},
            success: function (response) {
                if (response.status === 'error') {
                } else {
                }
            }
        })
    }) 
add_action('wp_ajax_export_to_excel', function () {
    global $wpdb;
    $table = $wpdb->prefix . 'custom';
    $lists= $wpdb->get_results("SELECT * FROM {$table }", ARRAY_A);
    $data = [];
    foreach ($lists as $list) {
        $data[] = [$lists['name'], $lists['url']];
    }
   SimpleXLSXGen::fromArray($data)->downloadAs('file.xlsx');
});
shuchkin commented 2 months ago

Try save XLSX to public folder and return url as result. Then document.location = result.xlsx_url

shuchkin commented 2 months ago

or see https://github.com/shuchkin/simplexlsxgen?tab=readme-ov-file#js-array-to-excel-ajax