1var colors = ["red", "blue", "green"];
2var colorsString = colors.join(","); //"red,blue,green"
1const arrayToCSV = (arr, delimiter = ',') =>
2 arr.map(v => v.map(x => `"${x}"`).join(delimiter)).join('\n');
1function exportToCsv(filename, rows) {
2 var processRow = function (row) {
3 var finalVal = '';
4 for (var j = 0; j < row.length; j++) {
5 var innerValue = row[j] === null ? '' : row[j].toString();
6 if (row[j] instanceof Date) {
7 innerValue = row[j].toLocaleString();
8 };
9 var result = innerValue.replace(/"/g, '""');
10 if (result.search(/("|,|\n)/g) >= 0)
11 result = '"' + result + '"';
12 if (j > 0)
13 finalVal += ',';
14 finalVal += result;
15 }
16 return finalVal + '\n';
17 };
18
19 var csvFile = '';
20 for (var i = 0; i < rows.length; i++) {
21 csvFile += processRow(rows[i]);
22 }
23
24 var blob = new Blob([csvFile], { type: 'text/csv;charset=utf-8;' });
25 if (navigator.msSaveBlob) { // IE 10+
26 navigator.msSaveBlob(blob, filename);
27 } else {
28 var link = document.createElement("a");
29 if (link.download !== undefined) { // feature detection
30 // Browsers that support HTML5 download attribute
31 var url = URL.createObjectURL(blob);
32 link.setAttribute("href", url);
33 link.setAttribute("download", filename);
34 link.style.visibility = 'hidden';
35 document.body.appendChild(link);
36 link.click();
37 document.body.removeChild(link);
38 }
39 }
40}
41
1var objectToCSVRow = function(dataObject) {
2 var dataArray = new Array;
3 for (var o in dataObject) {
4 var innerValue = dataObject[o]===null?'':dataObject[o].toString();
5 var result = innerValue.replace(/"/g, '""');
6 result = '"' + result + '"';
7 dataArray.push(result);
8 }
9 return dataArray.join(' ') + '\r\n';
10}
11
12var exportToCSV = function(arrayOfObjects) {
13
14 if (!arrayOfObjects.length) {
15 return;
16 }
17
18 var csvContent = "data:text/csv;charset=utf-8,";
19
20 // headers
21 csvContent += objectToCSVRow(Object.keys(arrayOfObjects[0]));
22
23 arrayOfObjects.forEach(function(item){
24 csvContent += objectToCSVRow(item);
25 });
26
27 var encodedUri = encodeURI(csvContent);
28 var link = document.createElement("a");
29 link.setAttribute("href", encodedUri);
30 link.setAttribute("download", "customers.csv");
31 document.body.appendChild(link); // Required for FF
32 link.click();
33 document.body.removeChild(link);
34}
35