Announcement

Export table data to excel using jquery


Export table data to excel using jquery

Export DataTable to Excel ©techiners
Export DataTable to Excel


To export data table to excel using jquery just add following code:




$('#btnExcel').click(function (e) {

window.open('data:application/vnd.ms-excel,'+$('#dvData').html());
e.preventDefault();


Explanation: #btnExcel is the id of the button on the click of which you need to export the data to the excel file. #dvData is the id of the DIV element in which data is present or rendered on the view that needs to be exported to excel file.


NOTE: Please try to run this code using IE. It might not work. For this the better solution is: here.

If its still not working then, try encoding the data table and then export it.

The updated code will look like this:

$('#btnExcel').click(function (e) {
window.open('data:application/vnd.ms-excel,' + encodeURIComponent($('#dvData').html()));
e.preventDefault();


Explanation: encodeURIComponent() is the method that will get the data as it is in the html page to excel file. As we might have seen QueryString in our address bar when we try to search anything on google, all spaces are replaced with '%20'. To get the exact data, we encode it and then send the data. Hence, encodeURIComponent() method is used.

No comments: