Export HTML table to CSV file

by pierian_design

HTML

<a href='#' onclick='downloadCSV({ filename: "stock-data.csv" });'>Download CSV</a>

CSS

* {
    color: #2b2b2b;
    font-family: "Roboto Condensed";
}

th {
    text-align: left;
    color: #4679bd;
}

tbody > tr:nth-of-type(even) {
    background-color: #daeaff;
}

button {
    cursor: pointer;
    margin-top: 1rem;
}

JavaScript

/*
    var stockData = [
        [
            "name:", "235"
        ],
        [
            "Zalupa:", "222"
        ],
        [
            "Cocy:", "Salo"
        ],
    ];
    
    
    
    
keys = Object.keys(data[0]);

result = '';
result += keys
.map(x => `"${x}"`)
.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;    
    
    
    
*/
	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;
        }
        
        console.log(data);

        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;
    }

    function downloadCSV() {
      var data, filename, link;
      var csv = convertArrayOfObjectsToCSV({
        data: stockData
      });
      if (csv == null) return;

      filename = 'YourFileNameHere.csv';

      var blob = new Blob([csv], {type:...