Skip to content

Instantly share code, notes, and snippets.

@marclundgren
Created March 31, 2017 22:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marclundgren/18527a0b62cc8f7199caf71ed4f0881c to your computer and use it in GitHub Desktop.
Save marclundgren/18527a0b62cc8f7199caf71ed4f0881c to your computer and use it in GitHub Desktop.
/*
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