Last active
March 12, 2019 11:42
-
-
Save kirpalmakanga/ed5877628a11040a9d3ed779d0b22b49 to your computer and use it in GitHub Desktop.
Client-side CSV export
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
function processRow(row, separator) { | |
let finalVal = ""; | |
for (let j = 0; j < row.length; j++) { | |
let innerValue = row[j] === null ? "" : row[j].toString(); | |
if (row[j] instanceof Date) { | |
innerValue = row[j].toLocaleString(); | |
} | |
let result = innerValue.replace(/"/g, '""'); | |
if (result.search(/("|,|\n)/g) >= 0) { | |
result = `"${result}"`; | |
} | |
if (j > 0) { | |
finalVal += separator; | |
} | |
finalVal += result; | |
} | |
return `${finalVal}\n`; | |
} | |
function createFileContent(rows, separator) { | |
let content = ""; | |
for (var i = 0; i < rows.length; i++) { | |
content += processRow(rows[i], separator); | |
} | |
return content; | |
} | |
function downloadFile(data, { fileName, type }) { | |
const blob = new Blob([data], { type }); | |
if (navigator.msSaveBlob) { | |
// IE 10+ | |
navigator.msSaveBlob(blob, fileName); | |
} else { | |
const link = document.createElement("a"); | |
if (link.download !== undefined) { | |
// feature detection | |
// Browsers that support HTML5 download attribute | |
const url = URL.createObjectURL(blob); | |
link.setAttribute("href", url); | |
link.setAttribute("download", fileName); | |
link.style.visibility = "hidden"; | |
document.body.appendChild(link); | |
link.click(); | |
document.body.removeChild(link); | |
} | |
} | |
} | |
function exportToCsv({ fileName, data, separator = "," }) { | |
const content = createFileContent(data, separator); | |
downloadFile(content, { | |
fileName: `${fileName}.csv`, | |
type: "text/csv;charset=utf-8;" | |
}); | |
} | |
const button = document.querySelector(".export"); | |
button.addEventListener("click", () => { | |
exportToCsv({ | |
fileName: "export", | |
data: [ | |
["name", "description"], | |
["david", "123"], | |
["jona", '""'], | |
["a", "b"] | |
], | |
separator: "," | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment