checkedresponsive[@]gmail.com

Menu

Generate CSV File in Javascript

How to Generate CSV File in Javascript

//JSON DATAS
var data = [
  ['Singaporean', 'Singapore'],
  ['Indian', 'India']
];

//CONVERT JSON Variant to TWO-DIMENSION Array

var csvContent = '';
data
.forEach(function(infoArray, index) {
dataString
= infoArray.join(';');
csvContent
+= index < data.length ? dataString + '\n' : dataString;
});

//Function to DOWNLOAD a file.
var download = function(content, fileName, mimeType) {
  var a = document.createElement('a');
  mimeType = mimeType || 'application/octet-stream';

  if (navigator.msSaveBlob) { // IE10
    navigator.msSaveBlob(new Blob([content], {
      type: mimeType
    }), fileName);
  } else if (URL && 'download' in a) { //html5 A[download]
    a.href = URL.createObjectURL(new Blob([content], {
      type: mimeType
    }));
    a.setAttribute('download', fileName);
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
  } else {
    location.href = 'data:application/octet-stream,' + encodeURIComponent(content); // only this mime type is supported
  }
}

download(csvContent, 'dowload.csv', 'text/csv;encoding:utf-8');

Leave a Reply

Your email address will not be published. Required fields are marked *