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

Question:

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

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)
Asked By: Nickpick

||

Answers:

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

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

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

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
Answered By: Satheesh

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"})
Answered By: Liam Roberts
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.