CSV download failed when csv file contain # value

705 views Asked by At

Data is broken if csv file contain a # value when i try to export csv data in vuejs.here is my code.Is it any encoding problem??

download_csv(){   
  var date = new Date();
  var hiddenElement = document.createElement('a');
  hiddenElement.href = 'data:text/csv;charset=utf-8,%EF%BB%BF' + encodeURI(this.CSVlogs);
  hiddenElement.target = '_blank';
  var today = moment(date).format('YYYY-MM-DD');
  hiddenElement.download = 'CWORK USERLIST_' + today + '.csv';
  hiddenElement.click();
},
2

There are 2 answers

0
Robert S On
let rows = ['id', 'date', 'extra columns']
let csvContent = 'data:text/csv;charset=utf-8,' + rows.join(',') + '\r\n'
let currentThis = this
this.data.forEach(function (row) {
  let container = [row.id, moment(row.date).format('DD MMMM YYYY').toString()]
    container.push(row.extra_column_data)
    csvContent += container.join(',') + '\r\n'
  })

let link = document.createElement('a')
link.setAttribute('href', encodeURI(csvContent))
link.setAttribute('download', 'csv_name.csv')
document.body.appendChild(link)
link.click()

you just need to pass the proper data to csv content

this code works for me

0
Rami Mohammed On

It is becouse the data contains # in which CSV taken as an end of line and breaks. So i replaced all the # values as space before it parsed to CSV file.

hiddenElement.href = 'data:text/csv;charset=utf-8,%EF%BB%BF' + encodeURI(this.CSVlogs.replace(/#/g,' '));