0

I test this Fiddle to implement a similar functionality on my project.

The export works great, but, In Windows I can't see the double quotes in the first value of every row.

enter image description here

I'd like to see "BMW" and "Honda CBR".

There is the code

    $(document).ready(function(){
    $('button').click(function(){
        var data = $('#txt').val();
        if(data == '')
            return;

        JSONToCSVConvertor(data, "Vehicle Report", true);
    });
});

function JSONToCSVConvertor(JSONData, ReportTitle, ShowLabel) {
    var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;

    var CSV = ''; 

    CSV += ReportTitle + '\r\n\n';
    if (ShowLabel) {
        var row = "";
        for (var index in arrData[0]) {
            row += index + ',';
        }

        row = row.slice(0, -1);
        CSV += row + '\r\n';
    }

    for (var i = 0; i < arrData.length; i++) {
        var row = "";
        for (var index in arrData[i]) {
            row += '"' + arrData[i][index] + '",';
        }

        row.slice(0, row.length - 1);
        CSV += row + '\r\n';
    }

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

    var fileName = "MyReport_";
    fileName += ReportTitle.replace(/ /g,"_");   

    var uri = 'data:text/csv;charset=utf-8,' + escape(CSV);

    var link = document.createElement("a");    
    link.href = uri;
    link.style = "visibility:hidden";
    link.download = fileName + ".csv";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

Any idea to solve this?

Thanks!

shaunhusain
  • 19,630
  • 4
  • 38
  • 51
ZizouJd
  • 79
  • 3
  • 12
  • Took off the angular tag since nothing in the question/code shows anything about angular https://stackoverflow.com/questions/14994391/thinking-in-angularjs-if-i-have-a-jquery-background <-- may also apply if you are in fact using this code with angular (DOM manipulation should only be done with directives) – shaunhusain Feb 07 '18 at 03:11
  • Ok @shaunhusain thanks! – ZizouJd Feb 07 '18 at 03:35
  • no problem here's another one more to the point of this question http://papaparse.com/ CSV parsing is more of a menace than you'd think with potential quoted strings and escaped commas etc. – shaunhusain Feb 07 '18 at 03:38
  • Fiddle showing correct results "BMW" and "Honda CBR" – Vinay Feb 07 '18 at 04:33

0 Answers0