Ask Your Question

Revision history [back]

click to hide/show revision 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:

  1. Create a button or link for downloading the CSV file.
<a href="#" id="download-link">Download CSV</a>
  1. Add an event listener to the button or link to trigger the download.
document.getElementById("download-link").addEventListener("click", downloadCSV);
  1. Define the 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();
}
  1. Test the download by clicking the button or link. A CSV file with the name table.csv should be downloaded containing the data from the HTML table.