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.Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2023-07-15 13:06:01 +0000
Seen: 11 times
Last updated: Jul 15 '23
What is the usage of JavaScript in IntelliJ IDEA Community Edition?
How can a custom loop function shape be altered to resemble Swift more accurately?
What is the issue with using java Gson().fromJson to assign BigDecimal values?
In what manner can I incorporate Java Enums into Amazon DynamoDB and AWS SDK v2?
How can Django Admin accommodate a variety of formats and locales for its input fields?