var a = [];
a.push(["Nombre", "Apellido", "Edad"]);
a.push(["Juan", "Lopez", 35]);
a.push(["Gas", "De la Llana", 32]);
a.push(["Cristian", "Bertelegni", 33]);
a.toCSV(); // return csv string
a.exportCSV(); // export csv file
Created
September 30, 2014 22:21
-
-
Save cbertelegni/2ff80e672a4080b535cf to your computer and use it in GitHub Desktop.
Extend Array prototype for export to csv.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Extend Array prototype: | |
Developer: @cbertelegni | |
Example: | |
var a = []; | |
a.push(["Nombre", "Apellido", "Edad"]); | |
a.push(["Juan", "Lopez", 35]); | |
a.push(["Cristian", "Bertelegni", 33]); | |
a.toCSV(); // return csv string | |
a.exportCSV(); // export csv file | |
*/ | |
Array.prototype.toCSV = function(){ | |
var arr = this; | |
var csvData = []; | |
for(var i = 0; i < arr.length; i++){ | |
var tmpArr = []; | |
for(var j = 0; j < arr.length; j++){ | |
var nodo = ""+arr[i][j]; | |
tmpStr = nodo.replace(/"/g, '""'); | |
tmpArr.push('"' + tmpStr + '"'); | |
} | |
csvData.push(tmpArr.join(',')); | |
} | |
var output = csvData.join('\n'); | |
return output; | |
}; | |
Array.prototype.exportCSV = function(file_name){ | |
var output = this.toCSV(); | |
if(!file_name) { | |
file_name = document.title ? document.title.replace(/ /g, "_") + ".csv" : "data.csv"; | |
} | |
var uri = 'data:text/csv;charset=utf-8,' + encodeURIComponent(output); | |
var downloadLink = document.createElement("a"); | |
downloadLink.href = uri; | |
downloadLink.download = file_name; | |
document.body.appendChild(downloadLink); | |
downloadLink.click(); | |
document.body.removeChild(downloadLink); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment