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

后端 未结 3 366
生来不讨喜
生来不讨喜 2020-12-23 22:35

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

相关标签:
3条回答
  • 2020-12-23 22:41

    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"})
    
    0 讨论(0)
  • 2020-12-23 22:57

    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
    
    0 讨论(0)
  • 2020-12-23 23:04

    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
    
    0 讨论(0)
提交回复
热议问题