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

时间:2015-08-05 05:13:04

标签: javascript json csv

从数组信息到csv:

<script>

    function downloadCsv() {
        var data = arrCsvData;
        var csvContent = "data:text/csv;charset=utf-8,";
        data.forEach(function(infoArray, index) {

            dataString = infoArray.join(",");
            csvContent += index < data.length ? dataString + "\n" : dataString;

        });

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

        link.click();
    }

</script>

同样如何将javascript json信息导出到csv(在客户端)?

2 个答案:

答案 0 :(得分:-1)

以下是我们如何将数组的json数组下载到cdv数据格式:

function downloadCsv() {
            var data = arrCsvData;
            var csvContent = "data:text/csv;charset=utf-8,";

                for (var key in data) {
                  if (data.hasOwnProperty(key)) {
                    data[key].unshift([key,""]);
                    for(var index=0;index<data[key].length;index++){
                        var elementArray = data[key][index];
                        data[key][index] = elementArray.join(",");
                    }
                    csvContent += data[key].join("\n");
                  }
                  csvContent += "\n";
                }
            var encodedUri = encodeURI(csvContent);
            var link = document.createElement("a");
            link.setAttribute("href", encodedUri);
            link.setAttribute("download", "graphData.csv");

            link.click();
        }

它对我有用:)

答案 1 :(得分:-1)

我自己实现了这个确切的问题。

它将JSON对象的JSON数组转换为Office 365 Excel中可读的CSV文件。

我用它将工作表转换为excel表。

    var jsonData = [
        {
            "Object": "Object",
            "AnotherObject": "AnotherValue"
        },
        {
            "Object": "SecondObject",
            "AnotherObject": "SecondValue"
        }
    ];
    WriteCSV(jsonData);

会在Excel中提供:

Screenshot Excel

Github page