Save HTML Table to Excel using jQuery
Friday, November 7th, 2008After 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>
