使用Flask将Pandas数据框转换为CSV并提供下载

34

我在Flask应用程序中有一个Pandas数据框,我想将其作为CSV文件返回。

return Response(df.to_csv())
问题是输出出现在浏览器中,而不是下载为单独的文件。我该如何改变它?
我也尝试了以下操作,但只得到了空输出。
response = make_response(df.to_csv())
response.headers['Content-Type'] = 'text/csv'
return Response(response)
3个回答

49

设置Content-Disposition来告诉浏览器下载文件而不是在页面上显示其内容。

resp = make_response(df.to_csv())
resp.headers["Content-Disposition"] = "attachment; filename=export.csv"
resp.headers["Content-Type"] = "text/csv"
return resp

我可以选择文件名吗? - Nickpick
文件名 = 想要的名称 + ".csv" ... "Content-Disposition": "attachment;" "filename={}".format(想要的名称) }``` - Dimo
我可以在这个响应中添加文本,以便在app.route上显示“您的文件已下载”吗? - Quantum Dreamer
有没有办法返回多个CSV文件? - Hamza usman ghani
@Hamzausmanghani,我不知道,抱歉) - MaxU - stand with Ukraine
1
@MaxU 我使用了zip文件来完成。解决方案 - Hamza usman ghani

12

这基本上是相同的解决方案,但是您可以将相同的信息传递给响应:

return Response(
       df.to_csv(),
       mimetype="text/csv",
       headers={"Content-disposition":
       "attachment; filename=filename.csv"})

5

设置内容分发并使用stringIO将数据框转换为流,以下是实现代码:

execel_file = StringIO.StringIO()
filename = "%s.csv" % ('output file')
df.to_csv(execel_file, encoding='utf-8')
csv_output = execel_file.getvalue()
execel_file.close()

resp = make_response(csv_output)
resp.headers["Content-Disposition"] = ("attachment; filename=%s" % filename)
resp.headers["Content-Type"] = "text/csv"
return resp

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接