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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38634862/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 01:41:13  来源:igfitidea点击:

Use Flask to convert a Pandas dataframe to CSV and serve a download

pythonpandasflask

提问by Nickpick

I have a Pandas dataframe in my Flask app that I want to return as a CSV file.

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

return Response(df.to_csv())

The problem is that the output appears in the browser instead of downloading as a separate file. How can I change that?

问题是输出出现在浏览器中,而不是作为单独的文件下载。我怎样才能改变它?

I tried the following as well but it just gave empty output.

我也尝试了以下操作,但它只是给出了空输出。

response = make_response(df.to_csv())
response.headers['Content-Type'] = 'text/csv'
return Response(response)

回答by MaxU

Set the Content-Dispositionto tell the browser to download the file instead of showing its content on the page.

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

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

回答by Satheesh

set the content-disposition and use stringIO to convert dataframe to stream, below is the code to achieve,

设置 content-disposition 并使用 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

回答by Liam Roberts

This is pretty much the same solution but you can just pass the same info into Response:

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

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