Skip to content

Instantly share code, notes, and snippets.

@do-me
Created February 22, 2024 08:35
Show Gist options
  • Select an option

  • Save do-me/5418f6b46032c7253d228cb6c7de2c3b to your computer and use it in GitHub Desktop.

Select an option

Save do-me/5418f6b46032c7253d228cb6c7de2c3b to your computer and use it in GitHub Desktop.
Export all html tables to csv (sep=|)
function exportTableToCSV(filename) {
var csv = [];
var rows = document.querySelectorAll('table tr');
for (var i = 0; i < rows.length; i++) {
var row = [], cols = rows[i].querySelectorAll('td, th');
for (var j = 0; j < cols.length; j++) {
var cellText = cols[j].textContent.trim();
var link = cols[j].querySelector('a');
if (link) {
cellText += " (" + link.getAttribute('href') + ")";
}
row.push(cellText);
}
csv.push(row.join('|'));
}
// Download CSV file
downloadCSV(csv.join('\n'), filename);
}
function downloadCSV(csv, filename) {
var csvFile;
var downloadLink;
csvFile = new Blob([csv], {type: 'text/csv'});
downloadLink = document.createElement('a');
downloadLink.download = filename;
downloadLink.href = window.URL.createObjectURL(csvFile);
downloadLink.style.display = 'none';
document.body.appendChild(downloadLink);
downloadLink.click();
}
exportTableToCSV('filename.csv')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment