Created
October 2, 2024 21:55
-
-
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)
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 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