I am having a table in HTML which is spanned in both rows and columns and looks kinda complex. I need a way to export this table to CSV File on a button click.
The following is the code 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>
<tr>
<td>Seed</td>
<td><b>{{x.Seed}}</b></td>
<td>Seedless</td>
</tr>
<tr>
<td rowspan="2">Water</td>
<td>Sweet</td>
<td><b>{{x.Sweet}}</b></td>
<td>80%</td>
</tr>
<tr>
<td>Sour</td>
<td><b>{{x.Sour}}</b></td>
<td>10%</td>
</tr>
<tr>
<td rowspan="1">Weight</td>
<td>Body Wt</td>
<td ><b>{{x.weight}}</b></td>
<td>500gm</td>
</tr>
</tbody>
I have tried using this,
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();
}
But the output I am getting is not exactly what I have mentioned in the image. How to exactly import HTML table to CSV as it is. PS: Even more spaned rows and columns can be added