We can use window.open() to export table data into Excel or any required format. It is the easiest and simplest way of creating a file with data without server side trip. window.open() requires 2 input parameters for this-
- the required MIMEtype and
- element that contains our data table.
If you want to export your Gridview data, then place that Gridview inside a container (like DIV etc.) and supply the DIV to winodw.open(). Also, be noted that window.open() has its scope and limitations in terms of browser vendors and customizing output file name.
Recently, I got a thread on Microsoft's asp.net forum regarding exporting GridView/table/div data into MS Excel at client side. You can refer that link - http://forums.asp.net/t/1854204.aspx/1?Export+to+Excel
So, I decided to write this post in context of helping other needy toubleshooters.
This is the second version you are reading as first was to help a forum user only. You know GridView gets rendered into "table" format. So, if you are using asp.net and looking for your GridView then keep your GridView inside a div element to make it easy.
If you are just looking for code snippet that do magic job for our Excel-export then it is single line code as below -
window.open('data:application/vnd.ms-excel,' + $('div[id$=divTableDataHolder]').html());
Understanding how it works:
To export our table data, we are going to use window.open(). I know most of you would be definitely familiar with this version of the window.open()-
window.open(URL, name , specs , replace )
But here you will see its another version :
window.open (MIMEtype , replace ) //replace=> dataContainerItem
| |________ It takes the element from window opener
|___________ Default MIME type is "text/html"
We have to just specify our required MIMEtype and it does the job for us! So for converting into MS Excel, we will specify data:application/vnd.ms-excel as MIME type.
So we will create a simple html table inside a div as -
<button id="myButtonControlID">Export Table data into Excel</button>
window.open('data:application/vnd.ms-excel,' + encodeURIComponent( $('div[id$=divTableDataHolder]').html()));
I am giving you the ready-reference snippet that contains a single line of code window.open() to export table data into MS excel :)
You can get more details on jQuery website: http://forum.jquery.com/topic/anyway-to-export-html-table-to-excel
Blog Extended On: 21-July-2013
window.open() has its scope and limitations(ex IE not working & filename) that has been well explained in this post: Export to CSV using jQuery and html
In terms of huge data export, I have already tested with 2500 rows and it works fine and I am sure it will work for more than this figure also. You can see it live : http://jsfiddle.net/AnilAwadh/wJyWm/