Last active
November 18, 2021 20:00
-
-
Save wesleybliss/04630bcbb8ed6812fd9922cf24fee2b5 to your computer and use it in GitHub Desktop.
Download all tables as CSVs
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() { | |
const table2csv = table => { | |
const rows = [...table.querySelectorAll('tr')] | |
const csv = [] | |
if (rows.length < 20) return null | |
for (let i in rows) { | |
const ths = [...rows[i].querySelectorAll('th')] | |
const tds = [...rows[i].querySelectorAll('td')] | |
if (ths && ths.length) { | |
const entry = [] | |
for (let j in ths) { | |
entry.push('"' + ths[j].innerText + '"') | |
} | |
csv.push(entry.join(',')) | |
} | |
if (tds && tds.length) { | |
const entry = [] | |
for (let j in tds) { | |
entry.push('"' + tds[j].innerText + '"') | |
} | |
csv.push(entry.join(',')) | |
} | |
} | |
return csv.join('\n') | |
} | |
const createUID = () => Math.floor(Date.now() * Math.random()) | |
const sendData = async (data) => { | |
const url = 'http://localhost:3000' | |
const uid = createUID() | |
const file = new Blob(data, { type: 'text/csv;charset=utf-8' }) | |
const formData = new FormData() | |
/* for (const name in data) { | |
formData.append(name, data[name]) | |
} */ | |
formData.append('file', file, `${uid}.csv`) | |
return await fetch(url, { | |
method: 'POST', | |
body: formData, | |
}) | |
} | |
const download = data => { | |
const file = new Blob([data], { type: 'text/csv;charset=utf-8' }) | |
const obj = URL.createObjectURL(file) | |
const link = window.document.createElement('a') | |
link.href = obj | |
link.download = createUID() | |
link.style.display = 'none' | |
document.body.appendChild(link) | |
link.click() | |
document.body.removeChild(link) | |
URL.revokeObjectURL(file) | |
} | |
const main = async () => { | |
const tables = document.querySelectorAll('table') | |
const csvs = [...tables].map(table2csv).filter(Boolean) | |
console.log('Converted', csvs.length, 'tables to csv, uploading') | |
/* for (let i in csvs) { | |
console.log('Upload', (i + 1), '/', csvs.length, '...') | |
try { await sendData() } | |
catch (e) { console.error(e) } | |
} */ | |
for (let i in csvs) { | |
console.log('Download', (i + 1), '/', csvs.length, '...') | |
download(csvs[i]) | |
} | |
} | |
main() | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment