Created
April 4, 2018 17:12
-
-
Save roxberry/c858c9cbb26ca85453f23c734271bb68 to your computer and use it in GitHub Desktop.
ExportCSV
This file contains 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
this.exportCSV = function (data, reportTitle, showHeader) { | |
var fields = { | |
id: { header: "ID", index:0, show: true}, | |
... | |
} | |
var arrData = typeof data != 'object' ? JSON.parse(data) : data; | |
var CSV = ''; | |
CSV += reportTitle + '\r\n\n'; | |
if (showHeader) { | |
var row = ""; | |
for (var index in arrData[0]) { | |
if (fields[index.toLowerCase()].show) { | |
headerName = fields[index.toLowerCase()].header; | |
row += headerName + ','; | |
} | |
} | |
row = row.slice(0, -1); | |
CSV += row + '\r\n'; | |
} | |
for (var i = 0; i < arrData.length; i++) { | |
var row = ""; | |
for (var index in arrData[i]) { | |
if (fields[index.toLowerCase()].show) { | |
var val = ''; | |
if (arrData[i][index]) { | |
val = arrData[i][index].toString().replace(/"/g, '""'); | |
} | |
//var val = val.replace(/"/g, '\"'); | |
console.log(index); | |
row += '"' + val + '",'; | |
} | |
} | |
row.slice(0, row.length - 1); | |
CSV += row + '\r\n'; | |
} | |
if (CSV == '') { | |
alert("Invalid data"); | |
return; | |
} | |
var fileName = reportTitle; | |
csvData = new Blob([CSV], { type: 'text/csv' }); | |
var csvUrl = URL.createObjectURL(csvData); | |
var link = document.createElement("a"); | |
link.href = csvUrl; | |
link.style = "visibility:hidden"; | |
link.download = fileName + ".csv"; | |
document.body.appendChild(link); | |
link.click(); | |
document.body.removeChild(link); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment