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

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

    If you are looking for a really quick solution you can also give a chance to this small library which will create and download CSV file for you: https://github.com/mbrn/filefy

    Usage is very simple:

    import { CsvBuilder } from 'filefy';
    
    var csvBuilder = new CsvBuilder("user_list.csv")
      .setColumns(["name", "surname"])
      .addRow(["Eve", "Holt"])
      .addRows([
        ["Charles", "Morris"],
        ["Tracey", "Ramos"]
      ])
      .exportFile();
    
    0 讨论(0)
  • 2020-11-21 22:55

    There you go :

    <!doctype html>  
    <html>  
    <head></head>  
    <body>
    <a href='#' onclick='downloadCSV({ filename: "stock-data.csv" });'>Download CSV</a>
    
    <script type="text/javascript">  
        var stockData = [
            {
                Symbol: "AAPL",
                Company: "Apple Inc.",
                Price: "132.54"
            },
            {
                Symbol: "INTC",
                Company: "Intel Corporation",
                Price: "33.45"
            },
            {
                Symbol: "GOOG",
                Company: "Google Inc",
                Price: "554.52"
            },
        ];
    
        function convertArrayOfObjectsToCSV(args) {
            var result, ctr, keys, columnDelimiter, lineDelimiter, data;
    
            data = args.data || null;
            if (data == null || !data.length) {
                return null;
            }
    
            columnDelimiter = args.columnDelimiter || ',';
            lineDelimiter = args.lineDelimiter || '\n';
    
            keys = Object.keys(data[0]);
    
            result = '';
            result += keys.join(columnDelimiter);
            result += lineDelimiter;
    
            data.forEach(function(item) {
                ctr = 0;
                keys.forEach(function(key) {
                    if (ctr > 0) result += columnDelimiter;
    
                    result += item[key];
                    ctr++;
                });
                result += lineDelimiter;
            });
    
            return result;
        }
    
        window.downloadCSV = function(args) {
            var data, filename, link;
    
            var csv = convertArrayOfObjectsToCSV({
                data: stockData
            });
            if (csv == null) return;
    
            filename = args.filename || 'export.csv';
    
            if (!csv.match(/^data:text\/csv/i)) {
                csv = 'data:text/csv;charset=utf-8,' + csv;
            }
            data = encodeURI(csv);
    
            link = document.createElement('a');
            link.setAttribute('href', data);
            link.setAttribute('download', filename);
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
           }
    </script>  
    </body>  
    </html>  
    
    0 讨论(0)
  • 2020-11-21 22:55

    You can use the below piece of code to export array to CSV file using Javascript.

    This handles special characters part as well

    var arrayContent = [["Séjour 1, é,í,ú,ü,ű"],["Séjour 2, é,í,ú,ü,ű"]];
    var csvContent = arrayContent.join("\n");
    var link = window.document.createElement("a");
    link.setAttribute("href", "data:text/csv;charset=utf-8,%EF%BB%BF" + encodeURI(csvContent));
    link.setAttribute("download", "upload_data.csv");
    link.click(); 
    

    Here is the link to working jsfiddle

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

    In Chrome 35 update, download attribute behavior was changed.

    https://code.google.com/p/chromium/issues/detail?id=373182

    to work this in chrome, use this

    var pom = document.createElement('a');
    var csvContent=csv; //here we load our csv data 
    var blob = new Blob([csvContent],{type: 'text/csv;charset=utf-8;'});
    var url = URL.createObjectURL(blob);
    pom.href = url;
    pom.setAttribute('download', 'foo.csv');
    pom.click();
    
    0 讨论(0)
  • 2020-11-21 22:57

    Here's an Angular friendly version:

      constructor(private location: Location, private renderer: Renderer2) {}
    
      download(content, fileName, mimeType) {
    
        const a = this.renderer.createElement('a');
    
        mimeType = mimeType || 'application/octet-stream';
    
        if (navigator.msSaveBlob) {
    
          navigator.msSaveBlob(new Blob([content], {
            type: mimeType
          }), fileName);
        }
        else if (URL && 'download' in a) {
    
          const id = GetUniqueID();
    
          this.renderer.setAttribute(a, 'id', id);
          this.renderer.setAttribute(a, 'href', URL.createObjectURL(new Blob([content], {
            type: mimeType
          })));
    
          this.renderer.setAttribute(a, 'download', fileName);
    
          this.renderer.appendChild(document.body, a);
    
          const anchor = this.renderer.selectRootElement(`#${id}`);
    
          anchor.click();
    
          this.renderer.removeChild(document.body, a);
        }
        else {
          this.location.go(`data:application/octet-stream,${encodeURIComponent(content)}`);
        }
      };
    
    0 讨论(0)
提交回复
热议问题