Javascript:write a string with multiple lines to a csv file for downloading

StackOverflow https://stackoverflow.com/questions/23667074

  •  22-07-2023
  •  | 
  •  

سؤال

I am trying to write a string that has multiple lines (comes from the server side) into a csv file for user to download in browser. However, using my code, I only get the csv files with all the data in a single line. Here is my code:

function getReport(){
    var report = "a,b,c,d;1,2,3,4;";
    //console.log(report);
    var csvcontent="";
    while (report.indexOf(";")!=-1)
    {
        csvcontent=csvcontent+ report.substring(0,report.indexOf(";"))+"\n";
        report=report.substring(report.indexOf(";")+1);
    }

    console.log(csvcontent);
    var a = document.createElement('a');
    a.href     = 'data:attachment/csv,' + csvcontent;
    a.target   = '_blank';
    a.download = 'myFile.csv';
    document.body.appendChild(a);
    //console.log("ok");
    a.click();
}

In the downloaded csv file, all the data will in a single line a,b,c,d1,2,3,4. Can anyone tell me how to solve this problem? Thanks in advance!

هل كانت مفيدة؟

المحلول

Try this instead
a.href = 'data:text/csv;charset=utf-8;base64,' + window.btoa(csvcontent);
It converts the data to base64 which properly encodes the new line character. Why it doesn't work in your method I'm really not sure. One caveat is the btoa function won't work in older browsers check out this question for more information How can you encode a string to Base64 in JavaScript?

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top