I have a complex HTML table with rows and columns spanning different sections. I am looking for a way to export this table to a CSV file with just a click of a button.https://i.sstatic.net/OOPgg.png
Here is the code snippet for the table,
<table class="table table-bordered">
<thead class="thead-dark">
<tr>
<th scope="col">Fruit Name</th>
<th scope="col">Type</th>
<th scope="col" colspan="3">Features</th>
<th scope="col">Recommended Values</th>
</tr>
</thead>
<tbody ng-repeat="x in response">
<tr>
<th rowspan="6"><b>{{x.FruitName}}</b></th>
<td rowspan="6"><b>{{x.FruitType}}</b></td>
<td rowspan="3">Color</td>
<td>Outer </td>
<td><b>{{x.Outer}}</b></td>
<td>Green/Black</td>
</tr>
<tr>
<td>Inner</td>
<td><b>{{x.Inner}}</b></td>
<td>Red</td>
</tr>
... (remaining table content)
</tbody>
I attempted to use the following JavaScript function to convert the table into a CSV file on button click,
function exportTableToCSV(filename) {
var csv = [];
var rows = document.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);
csv.push(row.join(","));
}
downloadCSV(csv.join("\n"), filename);
}
function downloadCSV(csv, filename) {
var csvFile;
var downloadLink;
csvFile = new Blob([csv], {type: "text/csv"});
downloadLink = document.createElement("a");
downloadLink.download = filename;
downloadLink.href = window.URL.createObjectURL(csvFile);
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
downloadLink.click();
}
However, the output does not match what I expected based on the image provided. What would be the best approach to accurately import an HTML table into a CSV file while preserving all row and column spans? PS: Additional spanned rows and columns may need to be accommodated.