从烧瓶中返回pandas的excel文件

时间:2016-10-26 17:54:10

标签: python pandas 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

我尝试对它进行调整,以便它可以输出带有各种标签的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

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

任何解决方案都适用。

1 个答案:

答案 0 :(得分:2)

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

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)