Hey guys, Want to export your small/Large Table data with row header in excel.
Also, you want to put some color in first row. then you are in right place.
This code (few lines of code ) will export the same.
No rocket science required.
No external setup
Only Vanilla JavaScript
----------------------------------------------------------
HTML-:
<table id="exTable" border="1">
<thead class="lockedRecordsBg">
<tr>
<th>S#</th>
<th>name</th>
<th>Email</th>
<th>Phone</th>
<th>Country</th>
</thead>
<tbody>
<tr>
<td rel="client">1</td>
<td rel="regionName">Sudhir K Gupta</td>
<td rel="date">sudhirgupta.456@gmail.com</td>
<td rel="shift">+91 89********</td>
<td rel="shift">India</td>
</tr>
<tr>
<td rel="client">2</td>
<td rel="regionName">Sudhir K Gupta</td>
<td rel="date">test@gmail.com</td>
<td rel="shift">+91 89********</td>
<td rel="shift">USA</td>
</tr>
</tbody>
</table>
Javascript-:
<script>
function exportToExcel(tableID){
var tab_text="<table border='2px'><tr bgcolor='#87AFC6' style='height: 75px; text-align: center; width: 250px'>";
var textRange; var j=0;
tab = document.getElementById(tableID); // id of table
for(j = 0 ; j < tab.rows.length ; j++)
{
tab_text=tab_text;
tab_text=tab_text+tab.rows[j].innerHTML.toUpperCase()+"</tr>";
//tab_text=tab_text+"</tr>";
}
tab_text= tab_text+"</table>";
tab_text= tab_text.replace(/<A[^>]*>|<\/A>/g, ""); //remove if u want links in your table
tab_text= tab_text.replace(/<img[^>]*>/gi,""); //remove if u want images in your table
tab_text= tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); //remove input params
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) // If Internet Explorer
txtArea1.document.open("txt/html","replace");
txtArea1.document.write( 'sep=,\r\n' + tab_text);
txtArea1.document.close();
txtArea1.focus();
sa=txtArea1.document.execCommand("SaveAs",true,"sudhir123.txt");
}
sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));
}
return (sa);
}
</script>
Now Put button below the script (must) or put jquery window.load function for this click event.
otherwise it will not work.
<input type="button" value="export" onclick="exportToExcel('exTable')" />
Ads.