python - 用 flask 从 Pandas 返回excel文件

标签 python pandas flask

在 flask 中,我想返回一个 excel 文件作为输出。

此代码适用于 csv:

    out = StringIO()
    notification_df.to_csv(out)
    resp = make_response(out.getvalue())
    resp.headers["Content-Disposition"] = "attachment; filename=output.csv"
    resp.headers["Content-type"] = "text/csv"
    return resp

我尝试对其进行调整,以便它可以输出带有各种选项卡(源自 Pandas 数据框)的 excel 文件,但这不起作用:
output = StringIO()
writer = ExcelWriter(output)
trades_df.to_excel(writer, 'Tab1')
snapshots_df.to_excel(writer, 'Tab2')
# writer.close() # causes TypeError: string argument expected, got 'bytes'

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

问题是我收到错误 TypeError: string argument expected, got 'bytes'当我做 writer.close() 时。但是当我离开它时,我得到:Exception: Exception caught in workbook destructor. Explicit close() may be required for workbook.
任何解决方案都被认可。

最佳答案

对于那些最终来到这里的人来说,这应该有效:

from flask import Response
import io
buffer = io.BytesIO()

df = pd.read_excel('path_to_excel.xlsx', header=0)
df.to_excel(buffer)
headers = {
    'Content-Disposition': 'attachment; filename=output.xlsx',
    'Content-type': 'application/vnd.ms-excel'
}
return Response(buffer.getvalue(), mimetype='application/vnd.ms-excel', headers=headers)

关于python - 用 flask 从 Pandas 返回excel文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40269047/

相关文章:

python - 在 Python Flask 中,如何在取消转义之前访问完整的原始 URL

python - 如何在 Pygame 中插入 slider ?

python-3.x - 检查列值是否在另一列中,哪些值是列表

python-3.x - 如何在 pandas DataFrame 中跨列重新排序值?

python - 将numpy类型转换为python

django - 无效的 HTTP_HOST header : The domain name provided is not valid -- requests to dockerized django app using container name

python - 获取 pandas 子组的统计数据

python - Flask uWSGI - 导入错误 : No module named request

python - 如何使用 flask 和 mysql 动态创建表列名和插入值

python - 如何将单词分配给列表中的值?