It is quite easy to bind data from database, collection classes or to xml. Sometimes, it is also needed to export the data in a different files types, for example, excel. Both GridView and Excel can display similar data structures (tabular data) and it is helpful at times to export data from GridView to excel. In this example, I will show how to do that.
At first, the GridView needs to be declared. A button is also needed that when clicked will export the GridView to excel.
As can be seen, The GridView does not have data bound to it. I will bind data to it from an ArrayList as shown in an previous article. An arraylist is created that contains a number of Person objects.
The Person class is below.
Once the page is loaded, the GridView contains a tabular data of all the Person objects. When the button is clicked, it will export the data in the GridView to excel.
The AddHeader method of Response object sets the filename of the excel. The charset is set to “UTF-8” and content type is set to excel.
When the button is clicked, an error message “Control 'Grid1' of type 'GridView' must be placed inside a form tag with runat=server. ” is shown. To avoid this error, the VerifyRenderingInServerForm() method needs to be overridden as follows.