如何将JavaScript数组信息导出到csv(在客户端)?

2022-08-29 22:34:19

我知道有很多这种性质的问题,但我需要使用JavaScript来做到这一点。我正在使用并在数组中拥有所有属性信息,如下所示:Dojo 1.8

[["name1", "city_name1", ...]["name2", "city_name2", ...]]

任何想法,我可以把它导出到客户端?CSV


答案 1

你可以在原生JavaScript中做到这一点。您必须将数据解析为正确的CSV格式(假设您正在使用数组数组作为数据,如问题中所述):

const rows = [
    ["name1", "city1", "some other info"],
    ["name2", "city2", "more info"]
];

let csvContent = "data:text/csv;charset=utf-8,";

rows.forEach(function(rowArray) {
    let row = rowArray.join(",");
    csvContent += row + "\r\n";
});

或更短的方式(使用箭头函数):

const rows = [
    ["name1", "city1", "some other info"],
    ["name2", "city2", "more info"]
];

let csvContent = "data:text/csv;charset=utf-8," 
    + rows.map(e => e.join(",")).join("\n");

然后,您可以使用JavaScript和函数下载CSV文件,如下所示:window.openencodeURI

var encodedUri = encodeURI(csvContent);
window.open(encodedUri);

编辑:

如果要为文件指定一个特定名称,则必须以不同的方式执行操作,因为不支持使用该方法访问数据 URI。为了实现这一点,您可以创建一个隐藏的DOM节点并按如下方式设置其属性:window.open<a>download
var encodedUri = encodeURI(csvContent);
var link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", "my_data.csv");
document.body.appendChild(link); // Required for FF

link.click(); // This will download the data file named "my_data.csv".

答案 2

基于上面的答案,我创建了这个功能,我已经在IE 11,Chrome 36和Firefox 29上进行了测试

function exportToCsv(filename, rows) {
    var processRow = function (row) {
        var finalVal = '';
        for (var j = 0; j < row.length; j++) {
            var innerValue = row[j] === null ? '' : row[j].toString();
            if (row[j] instanceof Date) {
                innerValue = row[j].toLocaleString();
            };
            var result = innerValue.replace(/"/g, '""');
            if (result.search(/("|,|\n)/g) >= 0)
                result = '"' + result + '"';
            if (j > 0)
                finalVal += ',';
            finalVal += result;
        }
        return finalVal + '\n';
    };

    var csvFile = '';
    for (var i = 0; i < rows.length; i++) {
        csvFile += processRow(rows[i]);
    }

    var blob = new Blob([csvFile], { type: 'text/csv;charset=utf-8;' });
    if (navigator.msSaveBlob) { // IE 10+
        navigator.msSaveBlob(blob, filename);
    } else {
        var link = document.createElement("a");
        if (link.download !== undefined) { // feature detection
            // Browsers that support HTML5 download attribute
            var url = URL.createObjectURL(blob);
            link.setAttribute("href", url);
            link.setAttribute("download", filename);
            link.style.visibility = 'hidden';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
    }
}

例如:https://jsfiddle.net/jossef/m3rrLzk0/