没有标题Javascript JSON数组 - > CSV导出

时间:2016-05-09 12:05:56

标签: javascript json csv

嗨大家出口有效,但我没有标题:/

我不知道我的问题是什么 信息:我从数据库获取数据它是一个Json数组

有人可以帮助我吗?

我的代码:

        var csvContent = "data:text/csv;charset=utf-8,";
        $("#csv").click(function(){
        // Iterating through all the objects
         data.forEach(function (infoArray, index) {

         // Fetching all keys of a single object
         var _keys = Object.keys(infoArray);
         var dataString = [];

//Test for my heading   
    //  var heading = ["Timestamp ; ToolVersion ; MonitorType ; SerialNumber; MonitorRevision ; TestScript ; TestCase ;TestCaseVersion ;TestScope; Duration; Result; ClickCount ;MorbalWaitAverage; MorbalWaitMin ; MorbalWaitMax ; TimingProblems ; AbortedRetries ; OperationRetries ; AcknowledgeAverage ; IncreasedUpdateTime ; FalseScrolls "];
        //dataString.push(heading);

        if(index==0){
         [].forEach.call(_keys, function(inst, i){
            dataString.push(inst);
         });
         dataString = dataString.join(";");
         csvContent += index < data[0].length ? dataString + "\n" : dataString;
         dataString = [];
        } else{

        [].forEach.call(_keys, function(inst, i){
            dataString.push(infoArray[inst]);
         });


          dataString = dataString.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(); 

        });

1 个答案:

答案 0 :(得分:1)

这有效:

    //--------------------------- CSV EXPORT --------------------------------

    var csvContent = "data:text/csv;charset=utf-16,";
    $("#csv").click(function()
    {
        var _keys = Object.keys(data[0]);
        dataString = "_"+_keys.join(";");
        csvContent += dataString + "\n";
        // Iterating through all the objects
        data.forEach(function (infoArray, index) {

            var dataString = [];

            [].forEach.call(_keys, function(inst, i){
                dataString.push(infoArray[inst]);
             });
              dataString = dataString.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(); 

    });