About Me

My photo

one who looks outside, dreams
one who looks inside, awakens!!

Get FREE updates!! subscribe!!

Delivered by FeedBurner

Like it? Follow up!! :)

Oct 13, 2013

jQuery to export html table data into excel sheet

Simple script to export html table or PHP data to excel sheet using jQuery, without having to write separate script again in php.

The basic idea is to take the html data as a screen shot and render it into excel output using jQuery.

Here is how it is done.

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

 <div id="excelExportDivision">

<table cellpadding="5" cellspacing="5" border="1">
<tr>
          <th>Blog</th>
</tr>
<tr>
         <td>http://www.sreevathsabv.blogspot.com</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']; 
?>
    
NOTE: I HAVE MADE SOME CHANGES AS SOME OF MY FRIENDS HAVE COMMENTED THAT IT IS NOT WORKING. IT"S FIXED AND WORKING... :)
                                                                                 
This is as simple as i can suggest you to export the php data into excel sheet.

It is amazingly fast and reliable.

Subscribe for more cool codes and see the other links below for more cool stuff!!