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

前端 未结 29 1670
没有蜡笔的小新
没有蜡笔的小新 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:39

    Working for all languages

            function convertToCsv(fName, rows) {
            var csv = '';
            for (var i = 0; i < rows.length; i++) {
                var row = rows[i];
                for (var j = 0; j < row.length; j++) {
                    var val = row[j] === null ? '' : row[j].toString();
                    val = val.replace(/\t/gi, " ");
                    if (j > 0)
                        csv += '\t';
                    csv += val;
                }
                csv += '\n';
            }
    
            // for UTF-16
            var cCode, bArr = [];
            bArr.push(255, 254);
            for (var i = 0; i < csv.length; ++i) {
                cCode = csv.charCodeAt(i);
                bArr.push(cCode & 0xff);
                bArr.push(cCode / 256 >>> 0);
            }
    
            var blob = new Blob([new Uint8Array(bArr)], { type: 'text/csv;charset=UTF-16LE;' });
            if (navigator.msSaveBlob) {
                navigator.msSaveBlob(blob, fName);
            } else {
                var link = document.createElement("a");
                if (link.download !== undefined) {
                    var url = window.URL.createObjectURL(blob);
                    link.setAttribute("href", url);
                    link.setAttribute("download", fName);
                    link.style.visibility = 'hidden';
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                    window.URL.revokeObjectURL(url);
                }
            }
        }
    
    
    
        convertToCsv('download.csv', [
            ['Order', 'Language'],
            ['1', 'English'],
            ['2', 'Español'],
            ['3', 'Français'],
            ['4', 'Português'],
            ['5', 'čeština'],
            ['6', 'Slovenščina'],
            ['7', 'Tiếng Việt'],
            ['8', 'Türkçe'],
            ['9', 'Norsk bokmål'],
            ['10', 'Ελληνικά'],
            ['11', 'беларускі'],
            ['12', 'русский'],
            ['13', 'Українська'],
            ['14', 'հայերեն'],
            ['15', 'עִברִית'],
            ['16', 'اردو'],
            ['17', 'नेपाली'],
            ['18', 'हिंदी'],
            ['19', 'ไทย'],
            ['20', 'ქართული'],
            ['21', '中国'],
            ['22', '한국어'],
            ['23', '日本語'],
        ])
    
    0 讨论(0)
  • 2020-11-21 22:40

    Download CSV File

      let csvContent = "data:text/csv;charset=utf-8,";
      rows.forEach(function (rowArray) {
        for (var i = 0, len = rowArray.length; i < len; i++) {
          if (typeof (rowArray[i]) == 'string')
            rowArray[i] = rowArray[i].replace(/<(?:.|\n)*?>/gm, '');
          rowArray[i] = rowArray[i].replace(/,/g, '');
        }
    
        let row = rowArray.join(",");
        csvContent += row + "\r\n"; // add carriage return
      });
      var encodedUri = encodeURI(csvContent);
      var link = document.createElement("a");
      link.setAttribute("href", encodedUri);
      link.setAttribute("download", "fileName.csv");
      document.body.appendChild(link);
      link.click();
    
    0 讨论(0)
  • 2020-11-21 22:42

    You can do this in native JavaScript. You'll have to parse your data into correct CSV format as so (assuming you are using an array of arrays for your data as you have described in the question):

    const rows = [
        ["name1", "city1", "some other info"],
        ["name2", "city2", "more info"]
    ];
    
    let csvContent = "data:text/csv;charset=utf-8,";
    
    rows.forEach(function(rowArray) {
        let row = rowArray.join(",");
        csvContent += row + "\r\n";
    });
    

    or the shorter way (using arrow functions):

    const rows = [
        ["name1", "city1", "some other info"],
        ["name2", "city2", "more info"]
    ];
    
    let csvContent = "data:text/csv;charset=utf-8," 
        + rows.map(e => e.join(",")).join("\n");
    

    Then you can use JavaScript's window.open and encodeURI functions to download the CSV file like so:

    var encodedUri = encodeURI(csvContent);
    window.open(encodedUri);
    

    Edit:

    If you want to give your file a specific name, you have to do things a little differently since this is not supported accessing a data URI using the window.open method. In order to achieve this, you can create a hidden <a> DOM node and set its download attribute as follows:

    var encodedUri = encodeURI(csvContent);
    var link = document.createElement("a");
    link.setAttribute("href", encodedUri);
    link.setAttribute("download", "my_data.csv");
    document.body.appendChild(link); // Required for FF
    
    link.click(); // This will download the data file named "my_data.csv".
    
    0 讨论(0)
  • 2020-11-21 22:44

    Based on the answers above I created this function that I have tested on IE 11, Chrome 36 and Firefox 29

    function exportToCsv(filename, rows) {
        var processRow = function (row) {
            var finalVal = '';
            for (var j = 0; j < row.length; j++) {
                var innerValue = row[j] === null ? '' : row[j].toString();
                if (row[j] instanceof Date) {
                    innerValue = row[j].toLocaleString();
                };
                var result = innerValue.replace(/"/g, '""');
                if (result.search(/("|,|\n)/g) >= 0)
                    result = '"' + result + '"';
                if (j > 0)
                    finalVal += ',';
                finalVal += result;
            }
            return finalVal + '\n';
        };
    
        var csvFile = '';
        for (var i = 0; i < rows.length; i++) {
            csvFile += processRow(rows[i]);
        }
    
        var blob = new Blob([csvFile], { type: 'text/csv;charset=utf-8;' });
        if (navigator.msSaveBlob) { // IE 10+
            navigator.msSaveBlob(blob, filename);
        } else {
            var link = document.createElement("a");
            if (link.download !== undefined) { // feature detection
                // Browsers that support HTML5 download attribute
                var url = URL.createObjectURL(blob);
                link.setAttribute("href", url);
                link.setAttribute("download", filename);
                link.style.visibility = 'hidden';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            }
        }
    }
    

    For example: https://jsfiddle.net/jossef/m3rrLzk0/

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-11-21 22:46
    //It work in Chrome and IE ... I reviewed and readed a lot of answer. then i used it and tested in both ... 
    
    var link = document.createElement("a");
    
    if (link.download !== undefined) { // feature detection
        // Browsers that support HTML5 download attribute
        var blob = new Blob([CSV], { type: 'text/csv;charset=utf-8;' });
        var url = URL.createObjectURL(blob);            
        link.setAttribute("href", url);
        link.setAttribute("download", fileName);
        link.style = "visibility:hidden";
    }
    
    if (navigator.msSaveBlob) { // IE 10+
       link.addEventListener("click", function (event) {
         var blob = new Blob([CSV], {
           "type": "text/csv;charset=utf-8;"
         });
       navigator.msSaveBlob(blob, fileName);
      }, false);
    }
    
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    
    //Regards
    
    0 讨论(0)
提交回复
热议问题