【问题标题】:Flask response to excel file giving corrupt excel file烧瓶对excel文件的响应给出损坏的excel文件
【发布时间】:2019-07-17 00:55:51
【问题描述】:

我有一个有按钮的网站。当它被点击时,它会将一些 pandas 数据帧返回到一个 excel 文件中,并自动返回该 excel 文件作为下载。

它似乎工作正常,除了当我打开文件时,它似乎已损坏。它询问是否应该恢复某些选项卡。我正在使用下面的代码。任何建议表示赞赏这可能是什么原因。

import io
from flask.helpers import make_response
from pandas.io.excel import ExcelWriter

output = io.BytesIO()
writer = ExcelWriter(output)

dfs = [df1,df2....]
tabs ['tab1','tab2',....]

for df, tab_name in zip(dfs, tab_names):
    df.to_excel(writer, tab_name)
writer.close()

resp = make_response(output.getvalue())
resp.headers['Content-Disposition'] = 'attachment; filename=output.xlsx'
resp.headers["Content-type"] = "text/csv"
return resp

【问题讨论】:

    标签: flask pandas.excelwriter


    【解决方案1】:

    你需要添加

    output.seek(0)
    

    关闭编写器后。

    您可能还会发现它更容易编写

    return send_file(output, attachment_filename="output.xlsx", as_attachment=True)
    

    (从flask导入send_file后)

    【讨论】:

    • 仍然有同样的问题,虽然 send_file 解决方案显然更优雅。
    • 问一个显而易见的问题,这是用app.route() 包裹的,不是吗?
    • 是的,它被包裹在@app.route
    • 问题是选项卡名称太长。 output.seek(0) 不是必需的
    • 嗯。回顾我的代码,我想我是从先前生成多个图像以保存到磁盘的代码中复制了该位,然后将 seek(0) 保留在其中,因为为什么不这样做。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-11
    • 1970-01-01
    • 1970-01-01
    • 2016-01-19
    相关资源
    最近更新 更多