0

I have to make a downloadable CSV file when click on the HTML button. I have created CSV data in my Javascript when click on the button. My question is how to write the data to a CSV file and make it downloadable. I have tried HTML5 download attribute to download the CSV file in client side. But HTML5 download attribute not supported by Internet Explorer. So I need to know how to pass the CSV data to ASPX and make it downloadable. Please advise. Thanks in advance.

2 Answers2

0

I have this code to download a csv from a webpage:

JS function:

function downloadCSV(csv_out) {
   var blob = new Blob([csv_out], { type: 'text/csv;charset=utf-8' });
   var url = window.URL || window.webkitURL;
   var link = document.createElementNS("http://www.w3.org/1999/xhtml", "a");
   link.href = url.createObjectURL(blob);
   link.download = "filename.csv";

   var event = document.createEvent("MouseEvents");
   event.initEvent("click", true, false);
   link.dispatchEvent(event);
}
Chris L
  • 2,262
  • 1
  • 18
  • 33
0

I am assuming you want to have Javascript only solution.
Then you can do following:

var looongCSVTEXT = ''
document.location ='data:Application/vnd.ms-excel,' +
        encodeURIComponent(looongCSVTEXT);

UPDATE:

on your page add

<input type='hidden' id='Hidden' runat='server' />

then in javascript (setting mechanism might be different, its up to you how you set CSV data to hidden control)

$('button').on('click', function(){ $('#Hidden').val(CSVData);});

then read the data from hidden control on the server side, and respond with excel file.
If you do not want to save it to disk first read this

Community
  • 1
  • 1
Matas Vaitkevicius
  • 58,075
  • 31
  • 238
  • 265