JavaScript array to CSV

后端 未结 9 885
不知归路
不知归路 2020-12-02 06:23

I\'ve followed this post How to export JavaScript array info to csv (on client side)? to get a nested js array written as a csv file.

The array looks like:



        
9条回答
  •  南笙
    南笙 (楼主)
    2020-12-02 06:59

    The selected answer is probably correct but it seems needlessly unclear.

    I found Shomz's Fiddle to be very helpful, but again, needlessly unclear. (Edit: I now see that that Fiddle is based on the OP's Fiddle.)

    Here's my version (which I've created a Fiddle for) which I think is more clear:

    function downloadableCSV(rows) {
      var content = "data:text/csv;charset=utf-8,";
    
      rows.forEach(function(row, index) {
        content += row.join(",") + "\n";
      });
    
      return encodeURI(content);
    }
    
    var rows = [
      ["name1", 2, 3],
      ["name2", 4, 5],
      ["name3", 6, 7],
      ["name4", 8, 9],
      ["name5", 10, 11]
    ];
    
    $("#download").click(function() {
      window.open(downloadableCSV(rows));
    });
    

提交回复
热议问题