Skip to content

Instantly share code, notes, and snippets.

@aXe1
Last active December 19, 2018 15:11
Show Gist options
  • Save aXe1/dfb5566ea67c83ebb88504b87c91dcc9 to your computer and use it in GitHub Desktop.
Save aXe1/dfb5566ea67c83ebb88504b87c91dcc9 to your computer and use it in GitHub Desktop.
Save any HTML table by CSS selector as CSV file from browser console

How to use

  1. Open browser console (Chrome, Edge: Ctrl + Shift + J, Firefox: Ctrl + Shift + K, Safari: Command + Option + C)
  2. Copy-paste html_table_to_csv.js contents and press Enter.
  3. Use function table_as_csv to download your data:
    table_as_csv("table"); // Use your own table selector here, and optionally filename
function download_data(data, filename, filetype) {
var file = new Blob([data], {type: filetype});
var downloadLink = document.createElement("a");
downloadLink.download = filename;
downloadLink.href = window.URL.createObjectURL(file);
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
downloadLink.click();
downloadLink.remove();
}
function table_to_csv(selector) {
var csv = [];
var html = document.querySelector(selector);
var rows = html.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++) {
row.push('"'+cols[j].innerText.replace(/\"/g, '""')+'"');
}
csv.push(row.join(","));
}
return csv.join("\n");
}
function table_as_csv(selector, filename = 'table.csv') {
download_data(table_to_csv(selector), filename, "text/csv");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment