Skip to content

Instantly share code, notes, and snippets.

@jonperron
Last active November 30, 2023 17:29
Show Gist options
  • Select an option

  • Save jonperron/733c3ead188f72f0a8a6f39e3d89295d to your computer and use it in GitHub Desktop.

Select an option

Save jonperron/733c3ead188f72f0a8a6f39e3d89295d to your computer and use it in GitHub Desktop.
Serve pandas dataframe as csv with Django
from django.http import HttpResponse
import pandas as pd
def foo():
results = pd.Dataframe()
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename=filename.csv'
results.to_csv(path_or_buf=response,sep=';',float_format='%.2f',index=False,decimal=",")
return response
@HungryGnu
Copy link
Copy Markdown

Thanks, you saved me a lot of time!

Copy link
Copy Markdown

ghost commented Oct 5, 2018

Thank you for posting that!

@danielalejandroamaro
Copy link
Copy Markdown

Thank you!!

@kittinan
Copy link
Copy Markdown

Thank you

@liuzheng1990
Copy link
Copy Markdown

Great post! Thanks. By the way, should the results.to_csv in the 10th line be your_dataframe.to_csv?

@jonperron
Copy link
Copy Markdown
Author

Yes indeed ! Thank you for spotting my typo

@DanielVF
Copy link
Copy Markdown

DanielVF commented Dec 6, 2019

Thank you for sharing!

@joeng03
Copy link
Copy Markdown

joeng03 commented May 4, 2020

Thanks a lot, this saved me a lot of time!

@deibanez
Copy link
Copy Markdown

deibanez commented Jul 1, 2020

genial!

@nitinraturi
Copy link
Copy Markdown

Thanks man, saved time

@fistons
Copy link
Copy Markdown

fistons commented Aug 18, 2020

Amazing!

@ioena07
Copy link
Copy Markdown

ioena07 commented Aug 30, 2020

Thank you so much! - it's brilliant!

@himanshu-patel-dev
Copy link
Copy Markdown

himanshu-patel-dev commented Oct 24, 2020

Thank you so much -- found it after a long struggle but really helpful.
between
results.to_csv(path_or_buf=response,sep=';',float_format='%.2f',index=False,decimal=",")
can be just
results.to_csv(path_or_buf=response)
if user do not want to go much in details of csv format and getting desired results.

@georgmzimmer
Copy link
Copy Markdown

perfect

@kadiagdg
Copy link
Copy Markdown

kadiagdg commented Dec 1, 2021

thank you so much !

@HOLL4ND
Copy link
Copy Markdown

HOLL4ND commented Mar 31, 2022

nice

@PingoLee
Copy link
Copy Markdown

Perfect

@harshavardhannarla
Copy link
Copy Markdown

Thank you

@Muhammadb1094
Copy link
Copy Markdown

That's good, worked in just 1st try.. Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment