将数组内容保存为csv文件js

时间:2016-09-20 13:41:22

标签: javascript arrays csv

我有一个包含另一个数组的数组。 我试图通过这个脚本将这个数组保存在csv文件中,但它不起作用。它没有下载我的文件...

    var data =(JSON.stringify(allFileGenesDetails1));
    var csvContent = '';
    data.forEach(function (infoArray, index) {
        dataString = infoArray.join(';');
        csvContent += index < data.length ? dataString + '\n' : dataString;
    });

    var download = function(content, fileName, mimeType) {
    var a = document.createElement('a');
        mimeType = mimeType || 'application/octet-stream';

        if (navigator.msSaveBlob) { // IE10
            return navigator.msSaveBlob(new Blob([content], { type: mimeType }), fileName);
        } else if ('download' in a) { //html5 A[download]
            a.href = 'data:' + mimeType + ',' + encodeURIComponent(content);
            a.setAttribute('download', fileName);
            document.body.appendChild(a);
            setTimeout(function() {
            a.click();
            document.body.removeChild(a);
            }, 66);
        return true;
    } else { //do iframe dataURL download (old ch+FF):
        var f = document.createElement('iframe');
        document.body.appendChild(f);
        f.src = 'data:' + mimeType + ',' + encodeURIComponent(content);

        setTimeout(function() {
            document.body.removeChild(f);
        }, 333);
        return true;
        }
    }

        download(csvContent, 'csv file.csv', 'text/csv');

1 个答案:

答案 0 :(得分:0)

以下是小提琴https://jsfiddle.net/51fbr4x9/1/,其中包含用于保存txt/csv而不使用Blob的示例代码。这是示例代码:

$(function() {
    var fileName = "test.csv";
    var table = [
        "colA1,colB1,colC1",
      "colA2,colB2,colC2"
    ];

    if ("download" in document.createElement("a")) {
        var link = $("<a target='_blank' href='data:text/csv;charset=utf-8,%EF%BB%BF" 
        + encodeURI(table.join("\n")) + "' download='" + fileName + "'></a>");
        link.appendTo("body");
        link[0].click();
        setTimeout(function () {
            link.remove();
        }, 50);
        return;  
    }

    var txt = $("<textarea cols='65536'></textarea>").get(0);
    txt.innerHTML = table.join("\n");
    var frame = $("<iframe src='text/csv;charset=utf-8' style='display:none'></iframe>").appendTo("body").get(0);
    frame.contentWindow.document.open("text/csv;charset=utf-8", "replace");
    frame.contentWindow.document.write(txt.value);
    frame.contentWindow.document.close();
    frame.contentWindow.document.execCommand("SaveAs", true, fileName);
    setTimeout(function () {
        $(frame).remove();
        $(txt).remove();
    }, 50);
});