我在将excel文件发送回烧瓶中的浏览器时遇到问题

时间:2019-10-11 22:23:03

标签: python python-3.x flask openpyxl

我正在尝试将excel文件发送回烧瓶中的用户浏览器。 excel文件是使用openpyxl创建的。

@app.route('/test', methods=['GET', 'POST'])
def test():
    if request.method == 'GET':

    ...

        buf = BytesIO()
        wb.save(buf)
        buf.seek(0)
        resp = make_response(buf)
            resp.headers["Content-Disposition"] = "attachment; filename=export.xlsx"
            resp.headers["Content-Type"] = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"

        return resp

出现以下错误:

TypeError:视图函数未返回有效响应。返回类型必须是字符串,字典,元组,Response实例或可调用的WSGI,但它是BytesIO。

如何在不使用BytesIO的情况下做到这一点?

非常感谢

1 个答案:

答案 0 :(得分:1)

尝试send_file

from flask import send_file
#...
def test():
    buf = BytesIO()
    # ...
    resp = send_file(buf)
    resp.headers["Content-Disposition"] = "attachment; filename=export.xlsx"
    resp.headers["Content-Type"] = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"