2

I have successfully managed to unparse a json to csv using papaparse. I have stored the generated csv in a variable. On a button click, the csv is being generated and I can see the result in my console. I want to download that csv generated into my local system when I click the button. How do I do that?

const csv = Papa.unparse(csvData);

Salman
  • 393
  • 1
  • 7
  • 23

1 Answers1

4

Try this code

var csv = Papa.unparse(array);

var csvData = new Blob([csv], {type: 'text/csv;charset=utf-8;'});

var csvURL = window.URL.createObjectURL(csvData);

var testLink = document.createElement('a');
testLink.href = csvURL;
testLink.setAttribute('test', 'test.csv');
testLink.click();
Salman
  • 393
  • 1
  • 7
  • 23
Pratik Patel
  • 5,995
  • 1
  • 18
  • 39
  • Are you we set csvURL to null. I am getting an error because of that. – Salman Feb 12 '19 at 14:28
  • try this var csvURL = window.URL.createObjectURL(csvData); Comment this line - var csvURL = null; – Pratik Patel Feb 12 '19 at 14:32
  • I tried this but nothing seems to happen on a click. Even in code pen when I click on the button nothing is being downloaded. Do you know what could be the problem? Is it working in your system through the button at code pen? – Salman Feb 12 '19 at 14:44
  • Perfect! it works now. Thats a lot for your help. Can you briefly explain what you did there? – Salman Feb 12 '19 at 14:48
  • i have just created blob object with your data. after this i have created a url using createurl whitch return the url represting object given in the parameter and then created tempopary hyperlink to download the file. for more detail visit https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL – Pratik Patel Feb 12 '19 at 15:52