-
-
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
This file contains 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
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