Skip to content

Instantly share code, notes, and snippets.

@Dewep
Created October 25, 2016 16:03
Show Gist options
  • Save Dewep/620091c301b8ed1fe923610a63072ee1 to your computer and use it in GitHub Desktop.
Save Dewep/620091c301b8ed1fe923610a63072ee1 to your computer and use it in GitHub Desktop.
JavaScript CSV Download
<!DOCTYPE>
<html>
<head>
<title>CSV</title>
</head>
<body>
<script type="text/javascript">
(function(){
function objectToCSV(content, separator) {
var str = ''
var formatValue = function (value) {
if (!isNaN(parseFloat(value)) && isFinite(value)) {
return value.toLocaleString('fr').replace(/ /g, '')
}
value += ''
return '"' + value.replace(/"/g, '""') + '"'
}
for (var line = 0; line < content.length; line++) {
if (line == 0) {
for (var column in content[line]) {
str += formatValue(column) + separator
}
str = str.slice(0, -1) + '\r\n'
}
for (var column in content[line]) {
str += formatValue(content[line][column]) + separator
}
str = str.slice(0, -1) + '\r\n'
}
return str
}
window.downloadCSV = function () {
var filename = "data.csv"
var content = [
{
id: 1,
title: "Hello world",
number: 4.67,
date: new Date()
},
{
id: 2,
title: "@Hello world 2",
number: -48.67,
date: new Date()
},
{
id: 3,
title: null,
number: 0,
date: new Date()
}
]
var csv = objectToCSV(content, ';')
var blob = new Blob(["\ufeff", csv], { type: 'text/csv;charset=utf-8;' })
if (window.navigator && window.navigator.msSaveBlob) {
window.navigator.msSaveBlob(blob, filename)
} else {
var link = document.createElement("a")
var url = window.URL.createObjectURL(blob)
link.setAttribute("href", url)
if (link.download !== undefined) {
link.setAttribute("download", filename)
link.style.visibility = 'hidden'
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
}
}
}
})()
</script>
<button onclick="downloadCSV()">Download CSV</button>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment