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">

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

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

You can call the function like so,  

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

….. and finally the export_file.php page.

  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.


Recommended Articles

Leave a Reply

Pin It on Pinterest