Advertisement
krot

csv export

Mar 6th, 2017
274
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var data = [['name1', 'city1', 'some other info'], ['name2', 'city2', 'more info']];
  2. var csvContent = '';
  3. data.forEach(function (infoArray, index) {
  4.   dataString = infoArray.join(';');
  5.   csvContent += index < data.length ? dataString + '\n' : dataString;
  6. });
  7.  
  8. var download = function(content, fileName, mimeType) {
  9.   var a = document.createElement('a');
  10.   mimeType = mimeType || 'application/octet-stream';
  11.  
  12.   if (navigator.msSaveBlob) { // IE10
  13.     return navigator.msSaveBlob(new Blob([content], { type: mimeType }), fileName);
  14.   } else if ('download' in a) { //html5 A[download]
  15.     a.href = 'data:' + mimeType + ',' + encodeURIComponent(content);
  16.     a.setAttribute('download', fileName);
  17.     document.body.appendChild(a);
  18.     a.click();
  19.     document.body.removeChild(a);
  20.     return true;
  21.   } else { //do iframe dataURL download (old ch+FF):
  22.     var f = document.createElement('iframe');
  23.     document.body.appendChild(f);
  24.     f.src = 'data:' + mimeType + ',' + encodeURIComponent(content);
  25.  
  26.     setTimeout(function() {
  27.       document.body.removeChild(f);
  28.     }, 333);
  29.     return true;
  30.   }
  31. }
  32.  
  33. download(csvContent, 'csv file.csv', 'text/csv');
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement