Skip to content

Instantly share code, notes, and snippets.

@waako
Forked from erd0s/rowspan.js
Created February 24, 2023 16:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save waako/73d0aaa6c12cf7018e862ae785d12d3d to your computer and use it in GitHub Desktop.
Save waako/73d0aaa6c12cf7018e862ae785d12d3d 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