Created
May 10, 2016 21:06
-
-
Save kareniel/d2ffca9bbefee2d5202730b100bdb27a to your computer and use it in GitHub Desktop.
AngularJS service that takes a collection and returns a CSV file download
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
exportcsv.$inject = ['$sce'] | |
function exportcsv($sce) { | |
const defaultOptions = { | |
filename: 'export' | |
} | |
return { toCSV } | |
/////// | |
function toCSV(arrToExport, options = defaultOptions) { | |
// returns an array of keys to be used as table header | |
const header = Object.keys(arrToExport[0]) | |
const propObject = header.reduce( (prev, curr) => { | |
prev[curr] = curr | |
return prev | |
}, {}) | |
arrToExport.unshift(propObject) | |
const csvData = arrToExport | |
.map( (obj) => { | |
const item = Object.keys(obj) | |
.map( (key) => [ `" ${obj[key]} ",` ] ) | |
.reduce( (prev, current) => prev.concat(current) ) | |
item.splice(item.length - 1, 1, "\n") | |
return item | |
}) | |
.reduce( (prev, current) => prev.concat(current) ) | |
.join('') | |
// add BOM to make sure special characters are read correctly | |
const BOM = "\uFEFF" | |
const output = BOM + csvData | |
const file = new Blob([output], { type: 'text/csv;charset=utf-8' }) | |
const url = $sce.trustAsResourceUrl(URL.createObjectURL(file)) | |
return function() { | |
const a = document.createElement("a") | |
a.href = url | |
a.style = "display: none" | |
a.download = options.filename + '.csv' | |
a.click() | |
}() | |
} | |
} | |
export default exportcsv |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment