Ask Your Question
2

How to convert an HTML table into a downloadable CSV file format?

asked 2023-07-15 13:06:01 +0000

bukephalos gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-07-15 13:26:01 +0000

pufferfish gravatar image

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.
edit flag offensive delete link more

Your Answer

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

Add Answer


Question Tools

Stats

Asked: 2023-07-15 13:06:01 +0000

Seen: 11 times

Last updated: Jul 15 '23