【问题标题】:Download Excel file with Ajax and Flask使用 Ajax 和 Flask 下载 Excel 文件
【发布时间】:2014-12-08 02:16:47
【问题描述】:

用户按下页面上 form 中包含的按钮:

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

单击按钮后,将进行以下 Ajax 调用:

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

在哪里

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);
    });
}

Flask 应用如下所示:

@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')

文件的文件内容被返回给浏览器(见下图),而不是文件本身作为附件。

问题是,回调需要是什么样子才能接受作为文件附件的响应?否则,需要进行哪些修改?

(是的,我已经搜索并阅读了 SE 上的许多帖子。大多数讨论使用 form.submit() 方法,但不提供详细信息。我希望避免使用 form.submit(),因为其中还有其他元素#form 不能提交。)

【问题讨论】:

  • 不确定this 帖子是否有帮助。尝试在您的回复中添加标题header('Content-Disposition: attachment; filename="name_of_excel_file.xls"');
  • 谢谢我看到那个帖子。在send_file方法中使用as_attachment=Truemimetype='application/vnd.ms-excel效果是一样的(我觉得)。

标签: javascript python ajax flask


【解决方案1】:

你真的需要使用 ajax 吗?我发现 ajax 是一种用烧瓶下载 excel 文件的解决方法……但它对我不起作用。 我只需在“rb”模式下打开 excel 文件并将 mimetype 更改为在 windows 中被识别为 excel 文件。您的 Flast 只需要调用 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"})

【讨论】:

    【解决方案2】:

    你可以使用Flask的send_from_directory function

    @app.route('/uploads/<path:filename>', methods=['GET', 'POST'])
    def download(filename):
        return send_from_directory(directory='uploads', filename=filename)
    

    【讨论】:

    • 这会自动设置 mimetime 和 headers 吗?
    【解决方案3】:

    我使用了不同的方法,而不是 Ajax,我创建了一个函数,每次选择更改时使用某个参数更新 href,在本例中是 country_id。

    HTML:

    <a type="button" class="btn btn-sm" id="export-excel" href="#">Download</a>
    

    在我写的脚本部分:

    function country_change(country_id)
    {
       var param = "/export_excel?";
       param += "country_id=" + country_id;
       $("a[id='export-excel']").attr('href', param);
    }
    

    因此,当您单击按钮时,href 已经更新。我的烧瓶部分是:

    @app.route('/export_excel')
    def export_excel ():
         country_id = request.args.get('country_id')
         obj = class_calc.calc()
         file_excel = obj.generate_excel(country_id)
         return send_file(file_excel, as_attachment=True, cache_timeout=0)
    

    工作正常。

    【讨论】:

      猜你喜欢
      • 2020-10-05
      • 1970-01-01
      • 2022-10-12
      • 2019-01-11
      • 1970-01-01
      • 1970-01-01
      • 2014-12-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多