Last active
November 5, 2020 14:05
-
-
Save CristalT/77ec6a83d68eba8a125c06ccc7d3ab7e to your computer and use it in GitHub Desktop.
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
/** | |
* @param data Object[] Ej.: [{ nombre: Marcelo, apellido: Forclaz }] | |
* @param fields Array Ej.: ['nombre', 'apellido'] | |
* @param columns Array Ej.: ['Nombre', 'Apellido'] | |
* @param filename String Ej.: 'archivo.csv' | |
* */ | |
const generateCsv = (data, fields, columns, filename) => { | |
let csv = 'data:text/csv;charset=utf-8,' | |
csv += '"' + columnNames.join('","') + '"\n'; | |
data.forEach(row => { | |
let csvrow = '' | |
fields.forEach(col => { | |
csvrow += `"${row[col]}",` | |
}) | |
csv += csvrow.substr(0, csvrow.length - 1).replace(/[";]/g, '') + '\n' | |
}) | |
const link = document.createElement('a') | |
link.setAttribute('href', csv) | |
link.setAttribute('download', filename.replace('.csv', '') + '.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