JS写入Json到CSV并下载

/*

CSV的格式是:

row1col1,row1col2,row1col3\r\n

row2col1,row2col2,row2col3\r\n

row3col1,row3col2,row3col3\r\n

思路很简单,拼凑字符串,避免特殊字符干扰CSV格式(西文双引号,逗号,换行等)。

 

下载的的方法是构建Url

data:text/csv;charset=UTF-8,Base32编码的csv字符串。

 

限制:

谷歌浏览器和IE浏览器对Url的最大长度限制不一样,总的来说,在前端组建CSV适用性非常有限,而且存在兼容性问题,不推荐使用。

*/

function JSONToCSVConvertor(JSONData, ReportTitle, ShowLabel) {
    var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;
    var CSV = "\ufeff";
    var firfixCSV = "\ufeff";
    if (ShowLabel) {
        var row = "";
        var firfixRow = "";
        for (var index in arrData[0]) {
            row += index + ',';
            firfixCSV += index + ',';
        }
        CSV += row.slice(0, -1) + '\r\n';
        firfixCSV = (firfixCSV.slice(0, -1) + '\n');
    }
    for (var i = 0; i < arrData.length; i++) {
        var row = "";
        for (var index in arrData[i]) {
            row += '"' + arrData[i][index] + '",';
            firfixCSV += arrData[i][index] + ',';
        }
        row.slice(0, row.length - 1);
        CSV += row + '\r\n';
        firfixCSV = (firfixCSV.slice(0, -1) + '\n');
    }

    if (CSV == '') {
        alert("Invalid data");
        return;
    }
    var link = document.createElement("a");
    link.id = "lnkDwnldLnk";
    document.body.appendChild(link);
    var csv = CSV;
    blob = new Blob([csv], { type: 'text/csv,charset=UTF-8', endings: 'native' });
    if (window.webkitURL) {
        var csvUrl = window.webkitURL.createObjectURL(blob);
    } else {
        var csvUrl = 'data:text/csv;charset=UTF-8,\ufeff' + encodeURIComponent(firfixCSV);
    }
    var filename = ReportTitle + '.csv';
    $("#lnkDwnldLnk")
    .attr({
        'download': filename,
        'href': csvUrl
    });
    $('#lnkDwnldLnk')[0].click();
    $('.bs-example-modal-lg').modal('hide');
    document.body.removeChild(link);
}

posted on 2017-05-05 11:05  Thancoo  阅读(2466)  评论(0编辑  收藏  举报

导航