Skip to content

Instantly share code, notes, and snippets.

@nguyenvanduocit
Created May 11, 2020 07:50
Show Gist options
  • Save nguyenvanduocit/84a2a4de51b48df890c8ac68d3c73287 to your computer and use it in GitHub Desktop.
Save nguyenvanduocit/84a2a4de51b48df890c8ac68d3c73287 to your computer and use it in GitHub Desktop.
Export elementIO table to csv
export function exportElTable (elTableRef) {
const data = dataHandler(elTableRef)
console.log(data)
exportCSVFile(data, 'product-analysis')
}
function dataHandler (elTableRef) {
let columns = elTableRef.columns
let data = elTableRef.data
let outputData = []
data.map((value) => {
let obj = {}
columns.forEach(element => {
console.log(element)
if (element.formatter) {
obj[element.label] = element.formatter(null, null, value[element.property], null)
} else {
obj[element.label] = value[element.property]
}
})
outputData.push(obj)
})
return outputData
}
export function convertToCSV (objArray) {
let array = typeof objArray !== 'object' ? JSON.parse(objArray) : objArray
let str = ''
for (let i = 0; i < array.length; i++) {
let line = ''
for (let index in array[i]) {
if (line !== '') line += ','
line += `"` + array[i][index] + `"`
}
str += line + '\r\n'
}
return str
}
export function exportCSVFile (items, fileTitle) {
let jsonObject = JSON.stringify(items)
let csv = convertToCSV(jsonObject)
let exportedFilenmae = fileTitle + '.csv' || 'export.csv'
let blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' })
if (navigator.msSaveBlob) { // IE 10+
navigator.msSaveBlob(blob, exportedFilenmae)
} else {
let link = document.createElement('a')
if (link.download !== undefined) { // feature detection
// Browsers that support HTML5 download attribute
let url = URL.createObjectURL(blob)
link.setAttribute('href', url)
link.setAttribute('download', exportedFilenmae)
link.style.visibility = 'hidden'
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