3

I'm working on Angular 2 in which I have to download data in CSV project. The problem is that I'm encountering comma in my data but that is manipulated as a new cell. I don't want that

{
    data.push({
        'Course Name' : item.courseName,
        'Course Type (ELICOS, Vocational Education, Higher Education)' 
        : item.courseTypeDisplay,
        'Total Cost' : item.totalCost,  
    })

    const header = Object.keys(data[0]);
    // let csv = data.map(row => header.map(fieldName => 
     JSON.stringify(row[fieldName], replacer)).join(','));
    let csv = data.map(row => header.map(fieldName => 
    row[fieldName]).join(','));
    csv.unshift(header.join(','));
    console.log(header);
    console.log(csv);
    let csvArray = "\ufeff"+csv.join('\r\n');

    var a = document.createElement('a');
    var blob = new Blob([csvArray], {type: 'text/csv;charset=UTF-8' }),
    url = window.URL.createObjectURL(blob);

    a.href = url;
    var date = new Date();
    var timeStamp = date.getTime();
    a.download = "Courses"+timeStamp+".csv";
    a.click();
    window.URL.revokeObjectURL(url);
    a.remove(); 
}

I want my result should show data => Course Type (ELICOS, Vocational Education or Training, Higher Education) in single-cell bit it is shown as cell 1 => Course Type (ELICOS , cell 2 => Vocational Education , cell 3 => Higher Education)

1
  • Instead of using this csv.unshift(header.join(',')); use this var header_new = JSON.stringify(header); var b = header_new.replace(/[[]']+/g,'') csv.unshift(b); Commented Sep 2, 2019 at 10:06

1 Answer 1

1
{
   data.push({
    'Course Name' : item.courseName,
    'Course Type (ELICOS, Vocational Education, Higher Education)' 
    : item.courseTypeDisplay,
    'Total Cost' : item.totalCost,  
   })

   const header = Object.keys(data[0]);
  // let csv = data.map(row => header.map(fieldName => 
  JSON.stringify(row[fieldName], replacer)).join(','));
  let csv = data.map(row => header.map(fieldName => 
  row[fieldName]).join(','));
  var header_new = JSON.stringify(header); 
  var b = header_new.replace(/[[]']+/g,'') 
  csv.unshift(b);
  console.log(header);
  console.log(csv);
  let csvArray = "\ufeff"+csv.join('\r\n');

  var a = document.createElement('a');
  var blob = new Blob([csvArray], {type: 'text/csv;charset=UTF-8' }),
  url = window.URL.createObjectURL(blob);

  a.href = url;
  var date = new Date();
  var timeStamp = date.getTime();
  a.download = "Courses"+timeStamp+".csv";
  a.click();
  window.URL.revokeObjectURL(url);
  a.remove(); 
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.