JSFiddle - React, Tailwind, and code Playground

by brigand

HTML

<button id="ExportExcel" type="Button">Export</button>
<table border=1>
  <thead>
    <tr>
      <th> P1 </th>
      <th> P2 </th>
      <th> P3 </th>
      <th> P4 </th>
      <th> P5 </th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Title</td>
      <td>Version</td>
      <td>Distros</td>
      <td>
        <ul>
          <li><a href="www.yahoo.com">Yahoo</a></li>
          <li><a href="www.google.com">Google</a></li>
          <li><a href="www.microsoft.com">Microsoft</a></li>
        </ul>
      </td>
      <td>Cat</td>
    </tr>

  </tbody>
</table>

JavaScript

function download_csv(csv, filename) {
  var csvFile;
  var downloadLink;

  // CSV FILE
  csvFile = new Blob([csv], {
    type: "text/csv"
  });

  // Download link
  downloadLink = document.createElement("a");

  // File name
  downloadLink.download = filename;

  // We have to create a link to the file
  downloadLink.href = window.URL.createObjectURL(csvFile);

  // Make sure that the link is not displayed
  downloadLink.style.display = "none";

  // Add the link to your DOM
  document.body.appendChild(downloadLink);

  // Launch
  downloadLink.click();
}


function export_table_to_csv(html, filename) {
  const csv = [];
  const rows = document.querySelectorAll("table tr");

  rows.forEach(tr => {
    const row = [],
      cols = tr.querySelectorAll("td, th");

    cols.forEach(column => {
      let text = "";
      column.childNodes.forEach(child => {
        if (child.nodeType === Node.ELEMENT_NODE && child.hasAttribute('href')) {
          text += ' ' + child.href;
        } else {
          text += ' ' + child.textContent;
        }
      });
      row.push(text.trim());
    });

    csv.push(row.join(","));
  });

  // Download CSV
  download_csv(csv.join("\n"), filename);
}


document.querySelector(".ExportExcel").addEventListener("click", function() {
  var html = document.querySelector("table").outerHTML;
  export_table_to_csv(html, "table.csv");
});