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

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

    One arrow function with ES6 :

    const dataToCsvURI = (data) => encodeURI(
    `data:text/csv;charset=utf-8,${data.map((row, index) =>  row.join(',')).join(`\n`)}`
    );
    

    Then :

    window.open(
      dataToCsvURI(
       [["name1", "city_name1"/*, ...*/], ["name2", "city_name2"/*, ...*/]]
      )
    );
    

    In case anyone needs this for reactjs, react-csv is there for that

    0 讨论(0)
  • 2020-11-21 22:47

    I added to Xavier Johns function to also include the field headers if needed, uses jQuery though. The $.each bit will need changing for a native javascript loop

    function exportToCsv(filename, rows, headers = false) {
        var processRow = function (row) {
            row = $.map(row, function(value, index) {
                return [value];
            });
            var finalVal = '';
            for (var j = 0; j < row.length; j++) {
                if(i == 0 && j == 0 && headers == true){
                    var ii = 0;
                    $.each(rows[i], function( index, value ) {
                        //console.log(index);
                        var fieldName = index === null ? '' : index.toString();
                        //console.log(fieldName);
                        var fieldResult = fieldName.replace(/"/g, '""');
                        //console.log(fieldResult);
                        if (fieldResult.search(/("|,|\n)/g) >= 0){
                            fieldResult = '"' + fieldResult + '"';
                        }
                        //console.log(fieldResult);
                        if (ii > 0){
                            finalVal += ',';
                            finalVal += fieldResult;
                        }else{
                            finalVal += fieldResult;
                        }
                        ii++;
                        //console.log(finalVal);
                    });
                    finalVal += '\n';
                    //console.log('end: '+finalVal);
                }
                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;
                }else{
                    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);
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-21 22:47

    Old question with many good answers, but here is another simple option that relies on two popular libraries to get it done. Some answers mention Papa Parse but roll their own solution for the download part. Combining Papa Parse and FileSaver.js, you can try the following:

    const dataString = Papa.unparse(data, config);
    const blob = new Blob([dataString], { type: 'text/csv;charset=utf-8' });
    FileSaver.saveAs(blob, 'myfile.csv');
    

    The config options for unparse are described here.

    0 讨论(0)
  • 2020-11-21 22:47

    From react-admin:

    function downloadCsv(csv, filename) {
        const fakeLink = document.createElement('a');
        fakeLink.style.display = 'none';
        document.body.appendChild(fakeLink);
        const blob = new Blob([csv], { type: 'text/csv' });
        if (window.navigator && window.navigator.msSaveOrOpenBlob) {
            // Manage IE11+ & Edge
            window.navigator.msSaveOrOpenBlob(blob, `${filename}.csv`);
        } else {
            fakeLink.setAttribute('href', URL.createObjectURL(blob));
            fakeLink.setAttribute('download', `${filename}.csv`);
            fakeLink.click();
        }
    };
    
    downloadCsv('Hello World', 'any-file-name.csv');
    
    0 讨论(0)
  • 2020-11-21 22:50

    This is a modified answer based on the accepted answer wherein the data would be coming from JSON.

                JSON Data Ouptut:
                 0 :{emails: "SAMPLE Co., peter@samplecompany.com"}, 1:{emails: "Another CO. , ronald@another.com"}
    
    
                JS:
                $.getJSON('yourlink_goes_here', { if_you_have_parameters}, function(data) {
                var csvContent = "data:text/csv;charset=utf-8,";
                var dataString = '';
                 $.each(data, function(k, v) {
                    dataString += v.emails + "\n";
                 });
    
                csvContent += dataString;
    
                var encodedUri = encodeURI(csvContent);
                var link = document.createElement("a");
                link.setAttribute("href", encodedUri);
                link.setAttribute("download", "your_filename.csv");
                document.body.appendChild(link); // Required for FF
    
                link.click();
            });
    
    0 讨论(0)
  • 2020-11-21 22:52

    The following is a native js solution.

    function export2csv() {
      let data = "";
      const tableData = [];
      const rows = [
        ['111', '222', '333'],
        ['aaa', 'bbb', 'ccc'],
        ['AAA', 'BBB', 'CCC']
      ];
      for (const row of rows) {
        const rowData = [];
        for (const column of row) {
          rowData.push(column);
        }
        tableData.push(rowData.join(","));
      }
      data += tableData.join("\n");
      const a = document.createElement("a");
      a.href = URL.createObjectURL(new Blob([data], { type: "text/csv" }));
      a.setAttribute("download", "data.csv");
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    }
    <button onclick="export2csv()">Export array to csv file</button>

    0 讨论(0)
提交回复
热议问题