gpt4 book ai didi

python - 用 flask 从 Pandas 返回excel文件

转载 作者:行者123 更新时间:2023-12-04 11:32:13 30 4
gpt4 key购买 nike

在 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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com