You are currently viewing How to download Pandas Dataframe as CSV in Django
How to download Panda Dataframe as CSV in Django

How to download Pandas Dataframe as CSV in Django

Spread the love

There can be three ways in which either we can download pandas dataframe or output the pandas dataframe as Excel or CSV in django. The ways are discussed below:-

How to download Panda Dataframe as CSV in Django
How to download Panda Dataframe as CSV in Django

Step 1 : download pandas dataframe by mounting our drive in Django

Follow following steps one by one

• Import drive and pandas library modules
• Mount your drive
• Paste the path of your file
• Get the id of the file
• Now create the file with the same id in your drive
• Now get the data of the file
• Read the data in csv format

from google.colab import drive
import pandas as pd
drive.mount(“content/drive”)
link = “link of the file to download”
id = link.split(“/”)[-2]
downloaded = drive.CreateFile({‘id’:id})
downloaded.GetContentFile(‘data.csv’)
df = pd.read_csv(“path where the file is downloaded in the drive”)

Step 2 : directly return response csv format in Django

• Import HttpResponse and pandas library
• Define a function which will return the response in the csv format
• Now initiate a dataframe object
• State the response type as text/csv
• Now attach the file name which you want to be printed
• Now read the file as you want using to_csv function

import pandas as pd
def fun():
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=",")

Step 3 : We can directly read the csv file using the url

With the help of below code line we directly read the csv file using the url

Import pandas as pd
url = “raw github link”
df1 = pd.read_csv(url)
print(df1.to_string())

Summary :

In this article we saw Three Steps for download Panda Dataframe as CSV in Django so about this article you have any query then free to ask me

BEST OF LUCK!!!

sachin Pagar

I am Mr. Sachin pagar Embedded software engineer, the founder of Sach Educational Support(Pythonslearning), a Passionate Educational Blogger and Author, who love to share the informative content on educational resources.

Leave a Reply