jQuery to export html table data into excel sheet

()

A simple script to export HTML table to excel using jquery or PHP data to excel sheet using jQuery, without having to write the separate script again in PHP.

The basic idea is to take the HTML data as a screenshot and render it into excel output using jQuery.

Wrap a div with an ID around the data that needs to be exported. Attach the form at the end of the data with a hidden text element

<div id="excelExportDivision">
  <table cellpadding="5" cellspacing="5" border="1">
    <tr>
      <th>Blog</th>
    </tr>
    <tr>
      <td>https://www.infoandapps.com/blog/</td>
    </tr>
  </table>
</div>

<form style="display:hidden" name="hiddenForm" id="hiddenForm" method="post" action="export_file.php">
  <input type="hidden" id="hiddenExportText" name="hiddenExportText">
</form>

<input type="button" value="Submit" onclick = "excel_export();">

Next, we will see a simple jQuery script, on click of which we trigger a page call, where headers for excel export is coded.

function excel_export(){
  
  var content = document.getElementById('excelExportDivision').innerHTML;
  
  $('#hiddenExportText').val(content);
  
  document.getElementById("hiddenForm").submit();	
}

You can call the function like so,  

<input type=”button” onclick=”excel_export();” value=”submit”/>

….. and finally the export_file.php page.

<?php
  header('Content-type: application/vnd.ms-excel');
  
  header("Content-Disposition: attachment; filename=BOBreport.xls");
  
  header("Pragma: no-cache");
  
  header("Expires: 0"); 
  
  echo $_REQUEST['hiddenExportText'];  
?>

Comment below and let us know if this was helpful or needs improvements.

Hit Like if this article was useful to you!

Average rating / 5. Vote count:

No votes so far! Be the first to rate this post.

As you found this post useful...

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Leave a Reply

Your email address will not be published. Required fields are marked *