Export html table in excel using javascript

During development in my current project i met with an interesting requirement like, I need to export a HTML table like structure using the Javascript. After some investigation i created a function which is below :

function excelExport(e, tableId, fileName) {
    if ( tableId !="" ){
        e.preventDefault();
        //getting data from our table
        var data_type = 'data:application/vnd.ms-excel';
        var table_div = document.getElementById(tableId);
        var table_html = table_div.outerHTML.replace(/ /g, '%20');
        var a = document.createElement('a');
        a.href = data_type + ', ' + table_html;
        a.download = fileName +'_' + Math.floor((Math.random() * 9999999) + 1000000) + '.xls';
        a.click();
    }
}

Now you are asking how to use this function in our code so below is my HTML code to explan how we can use above function in our code. Lets see -


<input type = "button" class="btn btn-primary" onclick="excelExport(event, 'excelExport', 'voice_artist_report');" value = "Export Excel"/>
<div id="divflow" style = "width : 100%;">
 <table   class = "gridtable" id="excelExport">
  <thead>
  <tr>
   <th>
    S.NO.
   </th>
   <th>
    Name
   </th>
   <th>
    Email
   </th>
   <th>
    Gender
   </th>
   <th>
    Country
   </th>
   </th>
   <th>
    Currency
   </th>
   <th>
    Native Language
   </th>
  </tr>
  </thead>
  <tbody>

  <?php
  $i = ($current_page * $items_on_page) - $items_on_page;
  foreach($formData['report_result']['table_data'] as $key => $value) {
   $i++;
   ?>
   <tr>
    <td>
     <?php echo $i;?>
    </td>
    <td>
     <?php echo $value['first_name'];?>
    </td>
    <td>
     <?php echo $value['email'];?>
    </td>
    <td>
     <?php echo $value['gender'];?>
    </td>
    <td>
     <?php echo $value['country'];?>
    </td>
    <td>
     <?php echo $value['currency'];?>
    </td>
    <td>
     <?php echo $value['native_language'];?>
    </td>
   </tr>

   <?php
  }
  ?>
  </tbody>
 </table>
</div>

Solution : Now you will see the Red Bold highlighted text in above html. Here i am passing three parameters onclick="excelExport(event, 'excelExport', 'voice_artist_report');
  1.  event = This is a default parameter. Don't change this.
  2.  tableId = excelExport is my table id.You can change it according to your table id.
  3.  fileName = voice_artist_report will be my exported excel file name. You can change it according to your requirenment. 

If you like this post don't forget to leave a comment.

Chears :)
Happy Coding

1 Comments

  1. HOẠT HÌNH CƯỚI - HOẠT HÌNH ỨNG DỤNG
    - QUẢNG CÁO 2ND.

    ReplyDelete
Previous Post Next Post