Export HTML Table to Excel Using JavaScript / JQuery
Simple Code
|
<script type="text/javascript">
function ExportToExcel(mytblId)
{
var
htmltable= document.getElementById(mytblId);
var
html = htmltable.outerHTML;
// MS OFFICE 2003 :
data:application/vnd.ms-excel
// MS OFFICE 2007 :
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
window.open('data:application/vnd.ms-excel,'
+ encodeURIComponent(html));
}
</script>
|
We can Customize our table data on the fly
using custom Export Function
Customize function to Export Data
|
<script type="text/javascript">
function CustomMethodToExport(tblId)
{
var
html ;
var
numofRows ;
var
gTable = document.getElementById(tblId);
numofRows = gTable.rows.length-1;
var
numofCells ;
var
trhtml = "";
numofCells = gTable.rows[0].cells.length-1 ;
for (
r = 0; r <= numofRows; r++)
{
var
c =0;
var
tdhtml = ""
;
for
(c = 0; c<=numofCells; c++)
{
var
tempstr = gTable.rows[r].cells[c].innerText
;
var
color = "" ;
var
isPercent = ""
if(tempstr.search("%") > 0)
{
if(tempstr.search('-') >= 0)
{
color = "red";
}
else
{
color = "green";
}
}
else
{
color = "black";
}
tdhtml = tdhtml + "<td style='text-align:right;color:"+
color +";'>" + gTable.rows[r].cells[c].innerText.replace(" ") + "</td>";
}
trhtml = trhtml + "<tr>" + tdhtml + "</tr>";
}
html = "<table
border='1'>"+trhtml+"</table>";
// MS OFFICE 2003 :
data:application/vnd.ms-excel
// MS OFFICE 2007 :
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
window.open('data:application/vnd.ms-excel,'
+ encodeURIComponent(html));
}
</script>
|
Export Data Using Jquery
|
$(window).load(function(){
$("#clickToExcel").click(function() {
var dtltbl = $('#mytbl').html();
window.open('data:application/vnd.ms-excel,' + $('# mytbl').html());
});
});//]]>
|
HTML Body Code
|
<body>
<form id="form1" runat="server">
<div>
<table id="mytbl" border="1">
<tr>
<td>
<b>ID</b></td>
<td>
<b>Name</b></td>
<td>
<b>Profit/Loss</b></td>
</tr>
<tr>
<td>
1</td>
<td>
Tarun</td>
<td>
200%</td>
</tr>
<tr>
<td>
2</td>
<td>
Ajay</td>
<td>
-200%</td>
</tr>
</table>
<a id="clickToExcel" href="javascript:ExportToExcel('mytbl')">Export
To Excel</a> | <a href="javascript:CustomMethodToExport('mytbl')">
Custome Export</a>
</div>
</form>
</body>
|
Note:
If you have special character problem then write down following
code before Window.open method inside script function
while (html.indexOf('á') != -1) html = html.replace('á', 'á');
while (html.indexOf('é') != -1) html = html.replace('é', 'é');
while (html.indexOf('Ã') != -1) html = html.replace('Ã', 'í');
while (html.indexOf('ó') != -1) html = html.replace('ó', 'ó');
while (html.indexOf('ú') != -1) html = html.replace('ú', 'ú');
while (html.indexOf('º') != -1) html = html.replace('º', 'º');
Use MIME
Type for MS Office 2003
application/vnd.ms-excel
Use MIME
Type for MS Office 2007 :
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet