Search code examples
javascriptjqueryhtmlexport-to-excel

HTML Table which contains check boxes, Need to Export HTML Table to Excel File for only the checked rows?


I had an HTML table in which one column is a checkbox. We can select any of the rows in that particular table. Now I need to export only the rows which are checked from the HTML table to excel file. How can I do it?

In the below Image i want to Export only the 1,2 and 5 rows which are checked to excel file.

image


Solution

  • This part allows you to get the data of the row in which the data has been selected

    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width">
      <title>JS Bin</title>
    </head>
    <body>
      <div id="here"></div>
      <table style="width:100%" id="table">
      <tr>
        <td><input class="checkMe" type="checkbox" />    &nbsp;   </td>
        <td>Jill</td>
        <td>Smith</td> 
        <td>4350</td>
      </tr>
      <tr>
        <td><input class="checkMe" type="checkbox" />    &nbsp;   </td>
        <td>Mark</td>
        <td>Kllis</td> 
        <td>5110</td>
      </tr>
      <tr>
        <td><input class="checkMe" type="checkbox" />    &nbsp;   </td>
        <td>Keath</td>
        <td>Marks</td> 
        <td>53210</td>
      </tr>
        </table>
      <button onclick="myFunction()">Click me</button>
    
      <script>
        function myFunction(){
          var checks = document.getElementsByClassName('checkMe');
          var table = document.getElementById('table')
    
          var element = document.getElementById("here");
          while (element.firstChild) {
            element.removeChild(element.firstChild);
          }
          for (var i = 0; i < table.rows.length; i++) {
            if(checks.item(i).checked == true){
              var fName = table.rows[i].cells[1].innerHTML; //first column  
              var lName = table.rows[i].cells[2].innerHTML; //first column  
              var num = table.rows[i].cells[3].innerHTML; //first column  
              var para = document.createElement("p");
              var node = document.createTextNode(fName + " " + lName + " "  + num);
              para.appendChild(node);
    
              element.appendChild(para); 
            }
          }
        }
      </script>
    
    </body>
    </html>
    

    For writing into to CSV there is already a great answer HERE and he made a cool code on fiddle which you can take a look at HERE