jQuery to export HTML table data into Excel sheet

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>http://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.

Shares

Recommended Articles

Leave a Reply

Pin It on Pinterest

Shares