Using javascript to download file as a.csv file

前端 未结 6 1448
难免孤独
难免孤独 2020-12-01 06:54

Hi I am trying to export a file as .csv file, so that when the user clicks on the download button, the browser would automatically download the file as .csv. I also want to

6条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-01 07:05

    If your data comes from a SQL Database, all your lines should have the same structure, but if coming from a NoSQL Database you could have trouble using standard answers. I elaborated on above JSON2CSV for such a scenario. Json data example

      [ {"meal":2387,"food":"beaf"},
        {"meal":2387,"food":"apple","peeled":"yes", "speed":"fast" },
        {"meal":2387,"food":"pear", "speed":"slow", "peeled":"yes" } ]
    

    Answer

    "meal","food","peeled","speed"
    "2387","beaf","",""
    "2387","apple","yes","fast"
    "2387","pear","yes","slow"
    

    Code for headers and double quotes for simplicity.

    function JSON2CSV(objArray) {
      var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
    
      var str = '';
      var line = '';
    
      // get all distinct keys      
      let titles = [];
      for (var i = 0; i < array.length; i++) {
        let obj = array[i];
        Object.entries(obj).forEach(([key,value])=>{
          //console.log('key=', key, "   val=", value );
          if (titles.includes(key) ) {
            // console.log (key , 'exists');
            null;
          }
          else {
            titles.push(key);
          }
        })
      }
      let htext =  '"' + titles.join('","') + '"';
      console.log('header:', htext);
      // add to str
      str += htext + '\r\n';
      //
      // lines
      for (var i = 0; i < array.length; i++) {
        var line = '';
        // get values by header order
        for (var j = 0; j < titles.length; j++) {
          // match keys with current header
          let obj = array[i];
          let keyfound = 0;    
          // each key/value pair
          Object.entries(obj).forEach(([key,value])=>{
            if (key == titles[j]) {
              // console.log('equal tit=', titles[j] , ' e key ', key ); // matched key with header
              line += ',"' + value +  '"';
              keyfound = 1; 
              return false;
            }
    
          })
          if (keyfound == 0) {
            line += ',"'  +  '"';   // add null value for this key
          } // end loop of header values
    
        }
    
        str += line.slice(1) + '\r\n';
      }
      return str;
    }
    

提交回复
热议问题