admin管理员组

文章数量:1401193

I am trying to write a string that has multiple lines (es 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!

I am trying to write a string that has multiple lines (es 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!

Share Improve this question asked May 14, 2014 at 23:54 KoshienKoshien 1561 silver badge9 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 8

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?

本文标签: Javascriptwrite a string with multiple lines to a csv file for downloadingStack Overflow