1 | initial version |
There are several ways to convert an HTML table into a downloadable CSV file format. Here is one way to do it using JavaScript:
<a href="#" id="download-link">Download CSV</a>
document.getElementById("download-link").addEventListener("click", downloadCSV);
downloadCSV
function that will convert the HTML table into a CSV file and download it.function downloadCSV() {
var table = document.querySelector("table"); // Get the HTML table element
var rows = table.querySelectorAll("tr"); // Get all the rows in the table
// Loop through the rows and create an array of arrays containing the cell values
var data = [];
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
var cells = row.querySelectorAll("td, th");
var rowData = [];
for (var j = 0; j < cells.length; j++) {
rowData.push(cells[j].innerText.trim());
}
data.push(rowData);
}
// Convert the array of arrays to a CSV string
var csv = data.map(function(row) {
return row.join(",");
}).join("\n");
// Create a download link and trigger the download
var link = document.createElement("a");
link.setAttribute("href", "data:text/csv;charset=utf-8," + encodeURIComponent(csv));
link.setAttribute("download", "table.csv");
link.click();
}
table.csv
should be downloaded containing the data from the HTML table.