7 Ocak 2020

Javascript Table To CSV

function isTable(element) {
    return (element.tagName == 'TABLE' || element.tagName == 'table')
}
function downloadCsv(csv, filename) {
    if (window.Blob == undefined
        || window.URL == undefined
        || window.URL.createObjectURL == undefined) {
        alert("Your browser doesn't support Blobs");
        return;
    }
    var BOM = "\uFEFF";
    var csvFile = new Blob([ BOM + csv], { type: "text/csv;" });
    var downloadLink = document.createElement("a");
    downloadLink.download = filename;
    downloadLink.href = window.URL.createObjectURL(csvFile);
    downloadLink.style.display = "none";
    document.body.appendChild(downloadLink);
    downloadLink.click();
}

function exportToCsv(id, filename, delimiter = ';') {
    tbl = document.getElementById(id);
    if (tbl != null && isTable(tbl)) {
        var rowArr = [];
        for (var j = 0; j < tbl.rows.length; j++) {
            var r = tbl.rows[j];
            var colArr = [];
            for (i = 0; i < r.cells.length; i++) {
                var c = r.cells[i];
                colArr.push(c.innerText);
            }
            rowArr.push(colArr.join(delimiter))
        }
    }
    downloadCsv(rowArr.join('\n'), filename);
}