Skip to content

Commit

Permalink
fix: handle comma, quotes & new line while exporting to csv
Browse files Browse the repository at this point in the history
  • Loading branch information
nextchamp-saqib committed Nov 20, 2024
1 parent f0badbf commit 899c68b
Showing 1 changed file with 20 additions and 1 deletion.
21 changes: 20 additions & 1 deletion frontend/src/query/resources/useQuery.js
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,26 @@ export default function useQuery(name) {
let data = [...results]
if (data.length === 0) return
data[0] = data[0].map((d) => d.label)
const csvString = data.map((row) => row.join(',')).join('\n')
const csvString = data
.map((row) => {
return row
.map((cell) => {
if (typeof cell === 'string') {
// if newline, wrap whole cell in quotes
// if double quote, prepend with another double quote
// if comma, wrap whole cell in quotes
if (cell.includes('"')) {
cell = cell.replace(/"/g, '""')
}
if (cell.includes('\n') || cell.includes(',') || cell.includes('"')) {
cell = `"${cell}"`
}
}
return cell
})
.join(',')
})
.join('\n')
const blob = new Blob([csvString], { type: 'text/csv' })
const url = window.URL.createObjectURL(blob)
const a = document.createElement('a')
Expand Down

0 comments on commit 899c68b

Please sign in to comment.