Home > Blockchain >  CSV download failed when csv file contain # value
CSV download failed when csv file contain # value

Time:05-10

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,'   encodeURI(this.CSVlogs);
  hiddenElement.target = '_blank';
  var today = moment(date).format('YYYY-MM-DD');
  hiddenElement.download = 'CWORK USERLIST_'   today   '.csv';
  hiddenElement.click();
},

CodePudding user response:

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

CodePudding user response:

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,' encodeURI(this.CSVlogs.replace(/#/g,' '));

  • Related