0

I have an array of time sheet data that I want to export as a csv file. My current implementation works great in Chrome, but not in Firefox or Safari (I haven't tested other browsers).

Here's an example of what I'm working with

rows = [
  ["Client", "Project", "User", "Duration (mins)", "Description", "Duration (hh:mm)"],
  ["foo", "foo_project", "foo bar", 30, "I did some stuff here", "0:30"],
  ["foo", "foo_project", "foo bar", 180, "And some more stuff during this one", "2:00"],
  ["bar", "bar_project", "foo bar", 9, "Only worked for nine minutes here", "0:09"]
]

data = "data:text/csv;charset=utf-8,"

joinedRows = rows.map(row => row.join(','))

data = data + joinedRows.join("\n")

link = document.createElement("a")

link.setAttribute('href', data)

link.click()

Running this snippet in Chrome will give you a properly formatted csv file, but in Firefox, it will all be one row.

Is the way that I'm creating data the right way to do it?

let el = document.getElementById('button')
el.addEventListener('click', () => {
  rows = [
    ["Client", "Project", "User", "Duration (mins)", "Description", "Duration (hh:mm)"],
    ["foo", "foo_project", "foo bar", 30, "I did some stuff here", "0:30"],
    ["foo", "foo_project", "foo bar", 180, "And some more stuff during this one", "2:00"],
    ["bar", "bar_project", "foo bar", 9, "Only worked for nine minutes here", "0:09"]
  ]

  data = "data:text/csv;charset=utf-8,"

  joinedRows = rows.map(row => row.join(','))

  data = data + joinedRows.join("\n")

  link = document.createElement("a")

  link.setAttribute('href', data)

  link.click()
})
<button id="button">Click to download</button>
james
  • 97
  • 1
  • 11
  • 2
    In cases like this it's better to use an established library that handles edge cases, and compatibility than inventing the wheels by yourself. I usually use [Papa Parse](https://www.papaparse.com/docs#json-to-csv) to convert from and to CSV. – Ori Drori Dec 13 '19 at 16:42
  • @OriDrori I'm hoping to not use a library for this, but I will definitely keep Papa Parse in my back pocket if I can't figure anything else out. – james Dec 13 '19 at 16:46
  • 1
    Does this answer your question? [How to export JavaScript array info to csv (on client side)?](https://stackoverflow.com/questions/14964035/how-to-export-javascript-array-info-to-csv-on-client-side) – Triby Dec 13 '19 at 16:53
  • @Triby It sure does! Thank you! – james Dec 13 '19 at 16:57

0 Answers0