Skip to content

Instantly share code, notes, and snippets.

@dulldesk
Created January 25, 2022 00:23
Show Gist options
  • Save dulldesk/528e3301932d689db013a9dad25440ad to your computer and use it in GitHub Desktop.
Save dulldesk/528e3301932d689db013a9dad25440ad to your computer and use it in GitHub Desktop.
Converts an HTML table to a CSV
function tableToCSV(elm="table",name="table") {
if (!(elm instanceof HTMLElement)) elm = document.querySelector(elm);
const data = new Array(...elm.getElementsByTagName("tr")).map(row => new Array(...row.querySelectorAll("td,th")).map(cell => cell.textContent.trim()).join(",")).join("\n");
const csv_blob = new Blob([data], {type: "text/csv"});
const url = URL.createObjectURL(csv_blob);
let tmp = document.createElement("a");
tmp.download = name + ".csv";
tmp.href = url;
tmp.style.display = "none";
document.body.appendChild(tmp);
tmp.dispatchEvent(new MouseEvent("click", {bubbles: false, cancelable: true, view: window}));
document.body.removeChild(tmp);
}
function selectTable() {
new Array(...document.querySelectorAll("table")).find(tbl => {
let origBorder = tbl.style.outline;
tbl.style.outline = "5px dashed red";
tbl.scrollIntoView();
if (confirm("Convert this table?")) {
tbl.style.outline = origBorder;
return tbl;
}
tbl.style.outline = origBorder;
});
}
tableToCSV(selectTable());
javascript:(() => {new Array(...document.querySelectorAll("table")).find(tbl => {let origBorder = tbl.style.outline; tbl.style.outline = "5px dashed red"; tbl.scrollIntoView(); if (confirm("Convert this table?")) {let tmp = document.createElement("a"); tmp.href = URL.createObjectURL(new Blob([new Array(...tbl.getElementsByTagName("tr")).map(row => new Array(...row.querySelectorAll("td,th")).map(cell => cell.textContent.trim()).join(",")).join("\n")], {type:"text/csv"} )); tmp.download = "table.csv"; tmp.style.display = "none"; document.body.appendChild(tmp); tmp.dispatchEvent(new MouseEvent("click", {bubbles: false, cancelable: true, view: window })); document.body.removeChild(tmp); tbl.style.outline = origBorder; return true; }; tbl.style.outline = origBorder; }); })()

JavaScript snippets to convert a table to a CSV file (tableToCSV()), with a helper function to select a table to convert (selectTable()) by traversing and prompting each table on the page.

The bookmarklet, on click, uses the two to find the desired table to convert. Add it by creating a regular bookmark and using the provided line for the URL field.

Code for table conversion is based off these two sources.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment