Skip to content

Instantly share code, notes, and snippets.

@chandra-prakash-meghwal
Last active October 12, 2024 10:26
Show Gist options
  • Save chandra-prakash-meghwal/dc12a60ccde4c276faf1f270edf0a93c to your computer and use it in GitHub Desktop.
Save chandra-prakash-meghwal/dc12a60ccde4c276faf1f270edf0a93c to your computer and use it in GitHub Desktop.
js code to download table data to csv
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