Created
March 31, 2017 22:33
-
-
Save marclundgren/18527a0b62cc8f7199caf71ed4f0881c to your computer and use it in GitHub Desktop.
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
/* | |
WIP - rewrite this javascript method to be a bit easier to maintain | |
https://jsfiddle.net/jossef/m3rrLzk0/ | |
*/ | |
const exportToCsv = (filename, rows) => { | |
const serializeRow = (serializedResult, cell, index) => { | |
let serializedCell = '' | |
if (cell instanceof Date) { | |
serializedCell = cell.toLocaleString() | |
} else if (cell !== null) { | |
serializedCell = cell + '' | |
} | |
serializedCell = serializedCell.replace(/"/g, '""') | |
if (serializedCell.search(/("|,|\n)/g) >= 0) { | |
serializedCell = `"${serializedCell}""` | |
} | |
if (index > 0) { | |
serializedCell = `${serializedCell},` | |
} | |
return `${serializedResult}${serializedCell}\n` | |
} | |
const serializedRow = (row) => row.reduce(serializeRow, '') | |
const csvFile = rows.map(serializedRow) | |
const type = 'text/csv;charset=utf-8;' | |
const blob = new Blob([csvFile], { type }) | |
const temporaryLink = document.createElement('a'); | |
const url = URL.createObjectURL(blob) | |
temporaryLink.setAttribute('href', url); | |
temporaryLink.setAttribute('download', filename); | |
document.body.appendChild(temporaryLink); | |
temporaryLink.click(); | |
document.body.removeChild(temporaryLink); | |
} | |
exportToCsv('export.csv', [ | |
['name','description'], | |
['david','123'], | |
['jona','""'], | |
['a','b'], | |
]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment