How to export JavaScript array info to csv (on client side)?

前端 未结 29 1736
没有蜡笔的小新
没有蜡笔的小新 2020-11-21 21:55

I know there are lot of questions of this nature but I need to do this using JavaScript. I am using Dojo 1.8 and have all the attribute info in array, which loo

29条回答
  •  Happy的楠姐
    2020-11-21 22:33

    I came here looking for a bit more RFC 4180 compliance and I failed to find an implementation, so I made a (possibly inefficient) one for my own needs. I thought I would share it with everyone.

    var content = [['1st title', '2nd title', '3rd title', 'another title'], ['a a a', 'bb\nb', 'cc,c', 'dd"d'], ['www', 'xxx', 'yyy', 'zzz']];
    
    var finalVal = '';
    
    for (var i = 0; i < content.length; i++) {
        var value = content[i];
    
        for (var j = 0; j < value.length; j++) {
            var innerValue =  value[j]===null?'':value[j].toString();
            var result = innerValue.replace(/"/g, '""');
            if (result.search(/("|,|\n)/g) >= 0)
                result = '"' + result + '"';
            if (j > 0)
                finalVal += ',';
            finalVal += result;
        }
    
        finalVal += '\n';
    }
    
    console.log(finalVal);
    
    var download = document.getElementById('download');
    download.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(finalVal));
    download.setAttribute('download', 'test.csv');
    

    Hopefully this will help someone out in the future. This combines both the encoding of the CSV along with the ability to download the file. In my example on jsfiddle. You can download the file (assuming HTML 5 browser) or view the output in the console.

    UPDATE:

    Chrome now appears to have lost the ability to name the file. I'm not sure what's happened or how to fix it, but whenever I use this code (including the jsfiddle), the downloaded file is now named download.csv.

提交回复
热议问题