Skip to content

Instantly share code, notes, and snippets.

@a666hn
Created December 19, 2020 08:56
Show Gist options
  • Save a666hn/828fad50bb28dbb9bc78126cf33b2979 to your computer and use it in GitHub Desktop.
Save a666hn/828fad50bb28dbb9bc78126cf33b2979 to your computer and use it in GitHub Desktop.
Generated data into csv with papaparse in javascript
function downloadCSV(csvTitle = "", csvHeader = [], csvData = []) {
// create filename using today unix time
const today = new Date().getTime()
const fileName = "Download-" + today + ".csv";
// Create title for csv
const title = csvTitle || "Download CSV example"
// Add header into first row
csvData.splice(0, 0, csvHeader)
let csv = papaparse.unparse({ fields: [title], data: csvData })
let csvBloob = new Blob([csv], { type: 'text/csv;charset=utf-8;' })
let csvURL = null
let link = document.createElement('a')
if (navigator.msSaveBlob) {
csvURL = navigator.msSaveBlob(csvBloob, 'download.csv')
} else {
csvURL = window.URL.createObjectURL(csvBloob)
}
link.href = csvURL
link.setAttribute('download', fileName)
link.click()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment