1

I am working on a task that needs to write to csv and download in the frontend. In views I have done:

...omitted details
data = data.values(*values_fields)
response = HttpResponse(content_type='text/csv')
writer = csv.DictWriter(response, fieldnames=values_fields)
writer.writeheader()
writer.writerows(data)
return response

And, in the frontend:

let a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
const blob = new Blob(res, {type: "text/csv"});
const url  = window.URL.createObjectURL(blob);
a.href = url;
a.download = 'data.csv';
a.click();
window.URL.revokeObjectURL(url);
a.remove()

First of all, when I inspect res, I have only seen arrays of integers instead of dictionaries. How can I download my data?

I figured it out that the response I am getting is in UTF-16 encoded array. I should decode it to UTF-8 -> meaningful strings then download it.

Tolga Bilbey
  • 119
  • 10
  • Do you have a working example of how you did it? I'm struggling to do the same. Here's my post https://stackoverflow.com/questions/67028612/export-download-csv-from-react-frontend-from-django – Aks Apr 09 '21 at 22:33
  • @Aks We actually changed our idea, and used Celery to create CVS, then upload it to the storage, after that we use the path of the csv. – Tolga Bilbey Apr 12 '21 at 11:19

1 Answers1

0

Not quite sure if this is the best solution for that, but this is how I've done it with an Excel sheet:

I saved the generated file to my server and then I'm doing this in my Django view:

    report = open(file_name, 'rb')
    response = HttpResponse(FileWrapper(report), content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response['Content-Disposition'] = 'attachment; filename='Report.xlsx'
    return response

In my React frontend I use js-file-download to download the file to the user's computer.

RaideR
  • 869
  • 1
  • 12
  • 33