fix(frontend): Download as CSV (#2000)

* fix(frontend): Download as CSV

* fix(frontend): Download as CSV
This commit is contained in:
Faton Ramadani
2023-08-07 18:16:28 +02:00
committed by GitHub
parent 57110b93c9
commit 5f3b2eacbf

View File

@@ -17,11 +17,30 @@
export let style = ''
export let download: boolean = true
function downloadResultAsJSON() {
const dataStr = 'data:text/json;charset=utf-8,' + encodeURIComponent(JSON.stringify(result))
function convertJSONToCSV(objArray: Record<string, any>[]) {
let str = ''
const headers = Object.keys(objArray[0])
str += headers.join(',') + '\r\n'
for (let i = 0; i < objArray.length; i++) {
let line = ''
for (let j = 0; j < headers.length; j++) {
const value = objArray[i][headers[j]]
line += j ? ',' : ''
line += /[\",\n]/.test(value) ? '"' + value.replace(/"/g, '""') + '"' : value
}
str += line + '\r\n'
}
return str
}
function downloadResultAsCSV() {
const csvStr = 'data:text/csv;charset=utf-8,' + encodeURIComponent(convertJSONToCSV(result))
const downloadAnchorNode = document.createElement('a')
downloadAnchorNode.setAttribute('href', dataStr)
downloadAnchorNode.setAttribute('download', 'data.json')
downloadAnchorNode.setAttribute('href', csvStr)
downloadAnchorNode.setAttribute('download', 'data.csv')
document.body.appendChild(downloadAnchorNode)
downloadAnchorNode.click()
downloadAnchorNode.remove()
@@ -69,7 +88,7 @@
variant="border"
color="light"
btnClasses="!py-1"
on:click={downloadResultAsJSON}
on:click={downloadResultAsCSV}
startIcon={{ icon: faDownload }}
>
Download