0

I am trying to export an array data to a csv file, which works fine unless it has break line("\n"). I hope to make it support break line in a single cell, is it possible?

I tried replace \n into "\n" or "'\n'" but it does not work

The function I am using:

function arrayToCSVConvertor(arrData, ReportTitle) {
    var CSV='';

    arrData.forEach(function(infoArray, index){
        var dataString = infoArray.join(",");
        //dataString= dataString.split('\n').join('\\n');//Here, need something to suport "\n"
        CSV += dataString+ "\n";
    });

    if (CSV == '') {
        alert("Invalid data");
        return;
    }

    //create a link and click then remove
    var link = document.createElement("a");
    link.id="lnkDwnldLnk";

    //this part will append the anchor tag and remove it after automatic click
    document.body.appendChild(link);

    var csv = CSV;
/*    window.open(encodeURI(csv));*/

    var blob = new Blob([csv], { type: 'text/csv' });
    //var csvUrl = window.webkitURL.createObjectURL(blob);
    var csvUrl = createObjectURL(blob);

    var filename = ReportTitle+'.csv';

    if(navigator.msSaveBlob){//IE 10
        return navigator.msSaveBlob(blob, filename);
    }else{
        $("#lnkDwnldLnk")
            .attr({
                'download': filename,
                'href': csvUrl
            });
        $('#lnkDwnldLnk')[0].click();
        document.body.removeChild(link);
    }
}

PS: I have Chinese words inside the array

JaskeyLam
  • 15,405
  • 21
  • 114
  • 149
  • Depends on the ["CSV" variant](https://en.wikipedia.org/wiki/Comma-separated_values). – user2864740 Jul 28 '15 at 04:36
  • For example: http://stackoverflow.com/questions/1241220/generating-csv-file-for-excel-how-to-have-a-newline-inside-a-value (also includes target/host - but again, see specific variant rules) – user2864740 Jul 28 '15 at 04:38

1 Answers1

0

I suggest avoiding the pain of working with CSV directly and all it's little variants and just use some library like Papa Parse to handle the job for you.

Basically, the new line to be used within a value should be a \n and the new line to end a record should be \r\n but as @user2864740 commented the results vary based on the encoding of the file and where you are going to open it.

Yoad Snapir
  • 528
  • 2
  • 10