Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download Excel file with Ajax and Flask

User presses a button contained within a form on the page:

<form id="form">
    <input type="button" id="export" value="Export"/>
</form>

Upon clicking the button, the following Ajax call is made:

ajaxCall('/export', {}, callback_export, 'get');

Where

function ajaxCall(url, params, callback, type) {
    if (validate()) {
        var request;
        request = $.ajax({
            url: url,
            type: type,
            data: params
        });
    }
    request.done(function (response, textStatus, jqXHR){
        callback(response);
    });
}

The Flask app looks like this:

@app.route('/export')
def export():
    xl_file= '/absolute/path/to/excel/file.xlsx'
    return send_file(xl_file, as_attachment=True, mimetype='application/vnd.ms-excel')

The file contents of the file are being returned to the browser (see image below) but not the file itself as an attachment.

Question is, what does the callback need to look like to accept the response as a file attachment? Or otherwise, what modifications need to be made?

(Yes, I've searched and read many of the posts on SE. Most discussing using the form.submit() method but do not provide details. I'm hoping to avoid using form.submit() as there are other elements within the #form that cannot be submitted.)

enter image description here

like image 734
Jason Strimpel Avatar asked Jan 09 '23 15:01

Jason Strimpel


1 Answers

You really need to use ajax? I found ajax is a work around to download excel files with flask...but it didn't work for me. I simply open excel file in 'rb' mode and change mimetype to be recognised as excel file in windows. Your Flast only need to call getPlotExcel().

@app.route("/getPlotExcel")
def getPlotExcel():
    excelDownload = open("sample.xlsx",'rb').read()
    return Response(
        excelDownload,
        mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        headers={"Content-disposition":
                 "attachment; filename=sample.xlsx"})
like image 153
Carlos Neves Avatar answered Jan 12 '23 09:01

Carlos Neves