Skip to content

Instantly share code, notes, and snippets.

@erd0s
Last active February 24, 2023 16:04
Show Gist options
  • Save erd0s/2d0593332c88bfb13dadbaa87d26cd9d to your computer and use it in GitHub Desktop.
Save erd0s/2d0593332c88bfb13dadbaa87d26cd9d to your computer and use it in GitHub Desktop.
Turn an HTML table with rowspans into a csv with rowspan data duplicated
var rows = document.querySelectorAll("table div table > tbody tr");
var records = [];
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
var cells = row.querySelectorAll("td");
cells.forEach((o, j) => {
// Put in the forward rows data
if (o.rowSpan > 1) {
for (var z = 1; z < o.rowSpan; z++) {
if (!records[i+z]) records[i+z] = [];
records[i+z][j] = o.innerText;
}
}
});
if (!records[i]) records[i] = [];
var bufferedTds = Array.prototype.slice.call(row.querySelectorAll("td"));
for (var cellIndex = 0; cellIndex < 6; cellIndex++) {
if (!records[i][cellIndex]) {
var item = bufferedTds.shift();
if (item) {
records[i][cellIndex] = item.innerText;
}
}
}
}
function toCSV(arr) {
var output = "";
arr.forEach((o, i) => {
o.forEach((p, j) => {
output += `"${p}"`;
if (j < o.length-1) {
output += ",";
}
});
output += "\n";
});
return output;
}
var csv = toCSV(records);
console.log(csv);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment