用烧瓶从熊猫返回excel文件

Nic*_*ick 5 python flask pandas

在烧瓶中,我想返回一个 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
Run Code Online (Sandbox Code Playgroud)

我尝试对其进行调整,以便它可以输出带有各种选项卡(源自熊猫数据框)的 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
Run Code Online (Sandbox Code Playgroud)

问题是我TypeError: string argument expected, got 'bytes'在执行 writer.close() 时遇到错误。但是当我离开它时,我得到:Exception: Exception caught in workbook destructor. Explicit close() may be required for workbook.

任何解决方案都被认可。

Man*_*oya 7

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

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)
Run Code Online (Sandbox Code Playgroud)