Created
March 25, 2025 16:00
-
-
Save signalwerk/157fe0b5243e99fcb70bd591407f33b6 to your computer and use it in GitHub Desktop.
Export HTML Table to CSV
This file contains hidden or 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 () { | |
// Option to toggle including hidden text in the CSV. | |
// When true, hidden text is included using textContent; | |
// When false, only visible text is included using innerText. | |
const includeHiddenText = true; | |
// Get all tables on the page. | |
const tables = document.querySelectorAll("table"); | |
if (!tables.length) { | |
alert("No table found on the page."); | |
return; | |
} | |
if (tables.length > 1) { | |
console.warn( | |
`Multiple tables found (${tables.length}). Using the first table.`, | |
); | |
} | |
// Use the first table found | |
const table = tables[0]; | |
const csv = []; | |
const rows = table.querySelectorAll("tr"); | |
// Process table rows | |
for (let i = 0; i < rows.length; i++) { | |
const row = []; | |
const cols = rows[i].querySelectorAll("th, td"); | |
// Process cells | |
for (let j = 0; j < cols.length; j++) { | |
const textMethod = includeHiddenText ? "textContent" : "innerText"; | |
let text = cols[j][textMethod]; | |
text = text.replace(/"/g, '""'); // Escape quotes | |
row.push('"' + text.trim() + '"'); | |
} | |
csv.push(row.join(",")); | |
} | |
// Create CSV download | |
const csvString = csv.join("\n"); | |
const blob = new Blob([csvString], { type: "text/csv;charset=utf-8;" }); | |
const url = URL.createObjectURL(blob); | |
const link = document.createElement("a"); | |
link.href = url; | |
link.download = "table.csv"; | |
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