export to csv with javascript

Solutions on MaxInterview for export to csv with javascript by the best coders in the world

showing results for - "export to csv with javascript"
Hildegard
09 Jun 2019
1function downloadCSV(csv, filename) {
2    var csvFile;
3    var downloadLink;
4
5    // CSV file
6    csvFile = new Blob([csv], {type: "text/csv"});
7
8    // Download link
9    downloadLink = document.createElement("a");
10
11    // File name
12    downloadLink.download = filename;
13
14    // Create a link to the file
15    downloadLink.href = window.URL.createObjectURL(csvFile);
16
17    // Hide download link
18    downloadLink.style.display = "none";
19
20    // Add the link to DOM
21    document.body.appendChild(downloadLink);
22
23    // Click download link
24    downloadLink.click();
25}
26//export
27function exportTableToCSV(filename) {
28    var csv = [];
29    var rows = document.querySelectorAll("table tr");
30    
31    for (var i = 0; i < rows.length; i++) {
32        var row = [], cols = rows[i].querySelectorAll("td, th");
33        
34        for (var j = 0; j < cols.length; j++) 
35            row.push(cols[j].innerText);
36        
37        csv.push(row.join(","));        
38    }
39
40    // Download CSV file
41    downloadCSV(csv.join("\n"), filename);
42}
43
similar questions
queries leading to this page
export to csv with javascript