I want to export the html table to csv file. In my case Html table consists of hyperlinks. While exporting html table to csv either the text or link is getting persisted in the table. I want the text to be persisted in the csv file as a hyperlink. Explored multiple solutions but none works. Tried adding whole anchor tag to variable and then adding to row, but whole anchor tag is appearing in the table in csv file. Needed quick help.
This is how the csv file should look like
<!DOCTYPE html>
<html>
<body>
<center>
<h1 style="color:green">GeeksForGeeks</h1>
<h2>Table to CSV converter</h2>
<table border="1" cellspacing="0" cellpadding="10">
<tr>
<th>Name</th>
<th>age</th>
<th>place</th>
</tr>
<tr>
<td><a href="https://www.codegrepper.com/code-examples/javascript/how+to+get+href+value+of+anchor+tag+in+jquery+in+list">Laxman</a></td>
<td>19</td>
<td>Hyderabad</td>
</tr>
<tr>
<td>Dhoni</td>
<td>22</td>
<td>Ranchi</td>
</tr>
<tr>
<td>Kohli</td>
<td>25</td>
<td>Delhi</td>
</tr>
</table>
<br><br>
<button type="button" onclick="tableToCSV()">
download CSV
</button>
</center>
<script type="text/javascript">
function tableToCSV() {
// Variable to store the final csv data
var csv_data = [];
// Get each row data
var rows = document.getElementsByTagName('tr');
for (var i = 0; i < rows.length; i++) {
// Get each column data
var cols = rows[i].querySelectorAll('td,th');
// Stores each csv row data
var csvrow = [];
for (var j = 0; j < cols.length; j++) {
// Get the text data of each cell
// of a row and push it to csvrow
var links = cols[j].getElementsByTagName('a');
if (links.length > 0) {
var link = links[0].getAttribute('href');
var text = cols[j].textContent;
var result = text.link(link)
csvrow.push(result);
} else {
var cellData = cols[j].textContent;
csvrow.push(cellData);
}
}
// Combine each column value with comma
csv_data.push(csvrow.join(","));
}
// Combine each row data with new line character
csv_data = csv_data.join('\n');
// Call this function to download csv file
downloadCSVFile(csv_data);
}
function downloadCSVFile(csv_data) {
// Create CSV file object and feed
// our csv_data into it
CSVFile = new Blob([csv_data], {
type: "text/csv"
});
// Create to temporary link to initiate
// download process
var temp_link = document.createElement('a');
// Download csv file
temp_link.download = "GfG.csv";
var url = window.URL.createObjectURL(CSVFile);
temp_link.href = url;
// This link should not be displayed
temp_link.style.display = "none";
document.body.appendChild(temp_link);
// Automatically click the link to
// trigger download
temp_link.click();
document.body.removeChild(temp_link);
}
</script>
</body>
</html>