Skip to content

Instantly share code, notes, and snippets.

@greenido
Created October 2, 2024 21:55
Show Gist options
  • Save greenido/c0f529544299f46b668dcdf1e9d8aee8 to your computer and use it in GitHub Desktop.
Save greenido/c0f529544299f46b668dcdf1e9d8aee8 to your computer and use it in GitHub Desktop.
Export a html table to a CSV file (just put this code in Chrome devtools)
// Function to convert HTML table to array
function tableToArray(tableId) {
const table = document.getElementById(tableId);
const rows = table.getElementsByTagName('tr');
const result = [];
for (let i = 0; i < rows.length; i++) {
const row = [];
const cells = rows[i].getElementsByTagName('td');
const headerCells = rows[i].getElementsByTagName('th');
// Handle header cells
for (let j = 0; j < headerCells.length; j++) {
row.push(headerCells[j].innerText.trim());
}
// Handle data cells
for (let j = 0; j < cells.length; j++) {
row.push(cells[j].innerText.trim());
}
if (row.length > 0) {
result.push(row);
}
}
return result;
}
// Function to convert array to CSV
function arrayToCSV(array) {
return array.map(row =>
row.map(cell =>
typeof cell === 'string' ? `"${cell.replace(/"/g, '""')}"` : cell
).join(',')
).join('\n');
}
// Function to download CSV
function downloadCSV(csv, filename) {
const csvFile = new Blob([csv], { type: 'text/csv' });
const downloadLink = document.createElement('a');
downloadLink.download = filename;
downloadLink.href = window.URL.createObjectURL(csvFile);
downloadLink.style.display = 'none';
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
}
// Main function to execute the conversion and download
function tableToCSV(tableId, filename = 'table_data.csv') {
const tableArray = tableToArray(tableId);
const csv = arrayToCSV(tableArray);
downloadCSV(csv, filename);
}
// Usage example:
// tableToCSV('yourTableId');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment