将数组数组导出为CSV [英] Exporting an array of arrays to CSV

查看:157
本文介绍了将数组数组导出为CSV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试遍历多维数组以将其导出为CSV.我尝试过在线复制一些指南,大多数指南似乎显示了与

I'm trying to loop through a multidimensional array to export it to CSV. I've tried to copy copy some of the guides online, and most seem to show similar solutions to How to export JavaScript array info to csv (on client side)? , however they all mention a const rows = where the array of information is entered. I've tried to modify this to loop through the arrays instead, but it's not prompting me to download the CSV, so I'm not sure if it's working. Can anyone advise what I'm doing wrong please.

function createCSV() {
    // loop the outer array
    for (var y = 0; y < properties.length; y++) {
        // get the size of the inner array
        var innerArrayLength = properties[y].length;
        // loop the inner array
        for (var z = 0; z < innerArrayLength; z++) {
            const rows = [
                [z]
            ];
            let csvContent = "data:text/csv;charset=utf-8,"
                + rows.map(e => e.join(",")).join("\n");
        }
    }

    var encodedUri = encodeURI(csvContent);
    var link = document.createElement("a");
    link.setAttribute("href", encodedUri);
    link.setAttribute("download", "my_data.csv");
    document.body.appendChild(link);

    link.click();
}

注意:这是对将对象导出并追加到csv 的改写.当我从使用对象更改为多维数组时,从根本上改变了问题

Note: this is a rephrasing of Export and append object to csv as I changed from using objects to multidimensional arrays, which fundamentally changed the question

推荐答案

我太复杂了.下面的代码起作用了,我创建了一个按钮来触发该功能,而不是强制单击.

I was over complicating it. The below code has worked and I've created a button to trigger the function, rather than forcing a click.

function createCSV() {
    var csv = "";
    properties.forEach(function(row) {
        csv += row.join(',');
        csv += "\n";
    });

    var hiddenElement = document.createElement('a');
    hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(csv);
    hiddenElement.target = '_blank';
    hiddenElement.download = 'properties.csv';
    hiddenElement.click();
}

这篇关于将数组数组导出为CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆