Save HTML Table to Excel using jQuery
November 7, 2008 – 2:47 pmAfter a few hours work looking into this, this turned out really easy to implement using jQuery and server side PHP programming as follows:
On the client side the following HTML code needs adding to the page:
<form action="/SaveToExcel.php" method="post" target="_blank" onsubmit='$("#datatodisplay").val( $("<div>"). append( $("#ReportTable").eq(0).clone() ).html() )'><input type="image" src="/images/icons/Floppy-48x48.png" width="12" height="12"><input type="hidden" id="datatodisplay" name="datatodisplay" /> </form>
Note - variables used above - ReportTable is the id of the table you want to save and datatodisplay is a hidden variable used to post the table to the server.
The jQuery commands were added to the form’s onsubmit event but could easily be in your $(function(){}); fuction
The hard part here was getting all of the <table> HTML code. The standard jQuery .html() command gets the innerHTML and was cutting off the <table> HTML code. Getting all the HTML code was accomplished using the code $(”#datatodisplay”).val( $(”<div>”).append( $(”#ReportTable”).eq(0).clone() ).html() ) which effectively gets the outerHTML of the named HTML object (in this case the table we want to save to excel).
On the server side create a file called’SaveToExcel.php’ and add the following code:
<?php
header("Content-type: application/vnd.ms-excel; name='excel'");
header("Content-Disposition: filename=export.xls");
header("Pragma: no-cache");
header("Expires: 0");
?>
<html>
<head></head>
<body><?=$_REQUEST['datatodisplay']?>
</body>
</html>

4 Responses to “Save HTML Table to Excel using jQuery”
well, I am not expert in jQuery but I think, sure this will work.. good luck.
By Kamal on Dec 6, 2008
Can you please explain me whats #datatodisplay and #reportTable are?
I get my table displayed in
and here is how is it passed.
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById(’display’);
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
Thanks in Advance.
By John on Dec 16, 2008
I figured that out.
Thanks,
How do i implement formula and format, any hints will be highly appreciated.
Thanks,
By John on Dec 16, 2008
Wow that worked! I was banging my head trying to find a .NET way to do this, but jQuery was much easier. Thanks John.
By Acrobatic on Dec 30, 2008