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

前端 未结 29 1699
没有蜡笔的小新
没有蜡笔的小新 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条回答
  •  长发绾君心
    2020-11-21 22:35

    Simply try this, some of the answers here are not handling unicode data and data that has comma for example date.

    function downloadUnicodeCSV(filename, datasource) {
        var content = '', newLine = '\r\n';
        for (var _i = 0, datasource_1 = datasource; _i < datasource_1.length; _i++) {
            var line = datasource_1[_i];
            var i = 0;
            for (var _a = 0, line_1 = line; _a < line_1.length; _a++) {
                var item = line_1[_a];
                var it = item.replace(/"/g, '""');
                if (it.search(/("|,|\n)/g) >= 0) {
                    it = '"' + it + '"';
                }
                content += (i > 0 ? ',' : '') + it;
                ++i;
            }
            content += newLine;
        }
        var link = document.createElement('a');
        link.setAttribute('href', 'data:text/csv;charset=utf-8,%EF%BB%BF' + encodeURIComponent(content));
        link.setAttribute('download', filename);
        link.style.visibility = 'hidden';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    };
    

提交回复
热议问题