2

This is a question concerning how to allow a user to export a Pandas dataframe to CSV format in Python 3.

For context, I have a Django view that accepts POST requests from jQuery, such that when a user clicks on a button on my website, it triggers a POST request to that Django view and performs some filtering to generate a Pandas dataframe. I want the users to be able to export the dataframe on their end, not into my personal local machine/project directory.

I make a sharp distinction between "downloading" and "exporting". Downloading can be easily done through the pd.to_csv method and basically saves the CSV file into a specified directory within my local machine (or my project folder, in fact). The problem is that the behavior I want is "exporting", which I define as when a user, upon clicking a button, is able to get the dataframe on their local machine.

The way I do "exporting" currently is by converting the Dataframe to an HTML table element, returning the HTML as the response of the POST request to jQuery, and use vanilla JS to inspect the table element to export the data on the user's end, following a protocol similar to How do I export html table data as .csv file?. The problem, however, is that when the dataframe grows too big, it becomes impossible to inspect the associated table element to generate a CSV file.

Any suggestion for exporting a Pandas dataframe to CSV is appreciated - it could be an original solution, in fact.

Yiftrer
  • 37
  • 1
  • 3
  • Your approach in the first section is correct. Once you get a **POST request**. use the ```pd.to_csv``` to convert it into a CSV file and save it in a directory in the server. Then you can create a method as per the answer in this thread https://stackoverflow.com/questions/36392510/django-download-a-file . And you can call the download() method, Thus now you can send the file as the response. https://stackoverflow.com/a/62013267/12889647 even this works. it is upto to you to choose – SARAN SURYA Mar 08 '22 at 03:29

2 Answers2

1

try this in your view function

import csv
import pandas as pd

def get(request):
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="{filename}.csv"'.format(filename='myname')
    writer = csv.writer(response)
    df = pd.DataFrame([{"name": "haha", "age": 18}, {"name": "haha", "age": 18}])
    writer.writerow([column for column in df.columns])
    writer.writerows(df.values.tolist())
    return response
        
paseca
  • 71
  • 3
1
df.to_csv(directory/file_name.csv')
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459