Exporting an array of arrays to CSV

我怕爱的太早我们不能终老 提交于 2019-12-13 03:46:59

问题


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();
}

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


回答1:


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();
}


来源:https://stackoverflow.com/questions/57542975/exporting-an-array-of-arrays-to-csv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!