How to export JavaScript array info to csv (on client side)?

前端 未结 29 2095
没有蜡笔的小新
没有蜡笔的小新 2020-11-21 21:55

I know there are lot of questions of this nature but I need to do this using JavaScript. I am using Dojo 1.8 and have all the attribute info in array, which loo

29条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-11-21 22:46

    This solution should work with Internet Explorer 10+, Edge, old and new versions of Chrome, FireFox, Safari, ++

    The accepted answer won't work with IE and Safari.

    // Example data given in question text
    var data = [
      ['name1', 'city1', 'some other info'],
      ['name2', 'city2', 'more info']
    ];
    
    // Building the CSV from the Data two-dimensional array
    // Each column is separated by ";" and new line "\n" for next row
    var csvContent = '';
    data.forEach(function(infoArray, index) {
      dataString = infoArray.join(';');
      csvContent += index < data.length ? dataString + '\n' : dataString;
    });
    
    // The download function takes a CSV string, the filename and mimeType as parameters
    // Scroll/look down at the bottom of this snippet to see how download is called
    var download = function(content, fileName, mimeType) {
      var a = document.createElement('a');
      mimeType = mimeType || 'application/octet-stream';
    
      if (navigator.msSaveBlob) { // IE10
        navigator.msSaveBlob(new Blob([content], {
          type: mimeType
        }), fileName);
      } else if (URL && 'download' in a) { //html5 A[download]
        a.href = URL.createObjectURL(new Blob([content], {
          type: mimeType
        }));
        a.setAttribute('download', fileName);
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
      } else {
        location.href = 'data:application/octet-stream,' + encodeURIComponent(content); // only this mime type is supported
      }
    }
    
    download(csvContent, 'dowload.csv', 'text/csv;encoding:utf-8');

    Running the code snippet will download the mock data as csv

    Credits to dandavis https://stackoverflow.com/a/16377813/1350598

提交回复
热议问题