Export HTML table to CSV file

Hello,

I am having a bit of trouble trying to find a way how to export html table into a csv file.

In my project, I use ESP32 as an AP and on the web page it is showing for clients, are values that are being measured.
I found this example on the internet, which works and downloads my data in the table, but it is a function which is called in a way I don't understand. It is called once a button is pushed, but I can't change which button. So it is downloaded when the first button on my page is pushed.

It doesn't matter in this example, but in my project it does. I have more buttons with other actions bound to them and I can't find a way how to have a little button on the bottom of the page and use that one for download.

Thank you for any suggestions!

The example:

<table>
    <tr><th>Name</th><th>Age</th><th>Country</th></tr>
    <tr><td>Geronimo</td><td>26</td><td>France</td></tr>
    <tr><td>Natalia</td><td>19</td><td>Spain</td></tr>
    <tr><td>Silvia</td><td>32</td><td>Russia</td></tr>
</table>


  </body>
  
   <div align="center">
      <button style="margin:2%; height:35px; width:90%; margin-top:40px;" onclick="exportTableToExcel('tblData')">Export Table Data To Excel File</button>
   </div>

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);

    // Lanzamos
    downloadLink.click();
}

function export_table_to_csv(html, filename) {
 var csv = [];
 var rows = document.querySelectorAll("table tr");
 
    for (var i = 0; i < rows.length; i++) {
 var row = [], cols = rows[i].querySelectorAll("td, th");
 
        for (var j = 0; j < cols.length; j++) 
            row.push(cols[j].innerText);
        
 csv.push(row.join(",")); 
 }

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

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

And this is my index.h which communicates with mine .ino file (which isn't important for this question so I won't show it here)

const char MAIN_page[] PROGMEM = R"=====(
<!DOCTYPE html>
<html>
<body>
<head> 
<!-- ======================== Načtení vzhledu tlačítek z tutorial webu ======================== -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
<!-- ======================== Nastavení tabulky ======================== -->   
    <style>
      tab-table, th, td {border: 1px solid black; border-collapse:collapse; text-align: center;}
    </style>
    
  </head>
<!-- ======================== Tlačítka ======================== -->
  <div id="demo" align="center">
      <button type="button" onclick="sendData(0)" class="btn btn-success" style="margin:2%;
      height:45px; width:40%; margin-top:40px;">Start</button>
      <button type="button" onclick="sendData(1)" class="btn btn-primary"style="margin:2%;
      height:45px; width:40%; margin-top:40px;">Pause</button>
  </div>
<!-- ======================== Tabulka ======================== -->
  <body>
    <table id="tblData" style="margin-top:20px; width:92.8%; margin-left:3.6%; ">
    
      <tr>
        <th style="height:45px; width:30%">Name</th>
        <th style="height:45px; width:25%">X location</th>
        <th style="height:45px; width:25%">Y location</th>
      </tr>
      
      <tr>
        <td bgcolor="#D3D3D3" style="height:45px; width:30%">Location 1</td>
        <td bgcolor="#D3D3D3" style="height:45px; width:25%"><span id="X0">N/A</span></td>
        <td bgcolor="#D3D3D3" style="height:45px; width:25%"><span id="Y0">N/A</span></td>
      </tr>
      
      <tr>
        <td style="height:45px; width:30%">Location 2</td>
        <td style="height:45px; width:25%"><span id="X1">N/A</span></td>
        <td style="height:45px; width:25%"><span id="Y1">N/A</span></td>
      </tr>
    </table>
  </body>
  
   <div align="center">
      <button style="margin:2%; height:35px; width:90%; margin-top:40px;" onclick="exportTableToExcel('tblData')">Export Table Data To Excel File</button>
   </div>
<!-- ======================== Část s kódem ======================== -->
  <script>
  <!-- ===== Funkce Stahování tabulky ===== -->    
    function exportTableToExcel(tableID, filename = 'Souradnice stredu'){
    var downloadLink;
    var dataType = 'application/vnd.ms-excel';
    var tableSelect = document.getElementById(tableID);
    var tableHTML = tableSelect.outerHTML.replace(/ /g, '%20');
    
    // Specify file name
    filename = filename?filename+'.xls':'excel_data.xls';
    
    // Create download link element
    downloadLink = document.createElement("a");
    
    document.body.appendChild(downloadLink);
    
    if(navigator.msSaveOrOpenBlob){
        var blob = new Blob(['\ufeff', tableHTML], {
            type: dataType
        });
        navigator.msSaveOrOpenBlob( blob, filename);
    }else{
        // Create a link to the file
        downloadLink.href = 'data:' + dataType + ', ' + tableHTML;
    
        // Setting the file name
        downloadLink.download = filename;
        
        //triggering the function
        downloadLink.click();
    }
}
  <!-- ===== Funkce tlačítek ===== -->
    function sendData(led){
      var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() 
      {
        if (this.readyState == 4 && this.status == 200) 
        {
          document.getElementById("LEDState").innerHTML =
          this.responseText;
        }
      };
      xhttp.open("GET", "setLED?LEDstate="+led, true);
      xhttp.send();
    }  
  <!-- ===== Funkce načítání hodnot do tabulky ===== -->
    setInterval(function(){ getData();},2000); 
    function getData() {
      var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
          if (this.readyState == 4 && this.status == 200) {
            document.getElementById("X0").innerHTML = this.responseText.split(",")[0];
            document.getElementById("Y0").innerHTML = this.responseText.split(",")[1];
            document.getElementById("X1").innerHTML = this.responseText.split(",")[2];
            document.getElementById("Y1").innerHTML = this.responseText.split(",")[3];
          }
        };
      xhttp.open("GET", "readValues", true);
      xhttp.send();
    }
  </script>
</body>
</html>
)=====";

So again, to sum it: I can't figure a way, how to call the function in example with a certain button.
My code is here just for the context of other buttons.

Thank you!

Buttons usually make a specific request to a server, which may not be important for this question. :wink:

zoomkat:
Buttons usually make a specific request to a server, which may not be important for this question. :wink:

Well yeah and that's why I am asking how is this making a request cause either it doesn't or I just don't understand how.

Still haven't found out. Does anybody have an idea? Thanks

FHan166:
Still haven't found out. Does anybody have an idea? Thanks

Well, you have an "xhttp" question which really doesn't have much to do with arduino programming. You might do a google search for something like "xhttp Get".