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)
By using pandas. DataFrame. to_csv() method you can write/save/export a pandas DataFrame to CSV File. By default to_csv() method export DataFrame to a CSV file with comma delimiter and row index as the first column.
Firstly you need to import from flask make_response , that will generate your response and create variable, something like response . Secondly, make response. content_type = "text/csv" Thirdly - return your response.
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
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"})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With