Search code examples
javascriptcsvexport-to-csv

JavaScript CSV Export


I'm generating CSV file via this code

export default function (name, data) {
  if (!data || !Array.isArray(data)) {
    return
  }
  name = name.length ? `${name}.csv` : 'export.csv'
  var csvData = new Blob([data.map(e => e.join(',')).join('\n')], { type: 'text/csv' })
  var csvUrl = URL.createObjectURL(csvData)
  const link = document.createElement('a')
  link.setAttribute('href', csvUrl)
  link.setAttribute('download', name)
  document.body.appendChild(link) // Required for FF
  link.click()
  document.body.removeChild(link)
}

But in Excel it opens row one column.

Is it possible to generate csv file that will show correct in Excel?


Solution

  • You could import the file in Excel and choose , as separator instead of just opening the file.


    Another option is to write the following as the first line (Excel specific):

    sep=,
    

    This will force Excel to use , as the separator.


    A third option is to use a different separator like TAB or ;. How Excel opens this depends on the (locale?) settings of the system.