Last active
October 12, 2024 10:26
-
-
Save chandra-prakash-meghwal/dc12a60ccde4c276faf1f270edf0a93c to your computer and use it in GitHub Desktop.
js code to download table data to csv
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function downloadTableAsCSV(tableId, filename) { | |
const rows = document.querySelectorAll(`#${tableId} tr`); | |
const csv = []; | |
for (const row of rows) { | |
const cols = row.querySelectorAll('td, th'); | |
const csvRow = Array.from(cols).map(col => { | |
const data = col.innerText.replace(/"/g, '""'); // Escape double quotes | |
return `"${data}"`; // Wrap in quotes | |
}).join(','); // Join columns with a comma | |
csv.push(csvRow); | |
} | |
const csvString = csv.join('\n'); // Join rows with a new line | |
const blob = new Blob([csvString], { type: 'text/csv;charset=utf-8;' }); | |
const link = document.createElement('a'); | |
link.href = URL.createObjectURL(blob); | |
link.setAttribute('download', filename); | |
document.body.appendChild(link); | |
link.click(); | |
document.body.removeChild(link); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment