Export HTML, Grid View and Image to Excel Sheet Using ASP.Net

Here I will show how to export a HTML table, grid view controls and image control to Excel sheet.

Here I will show how to export a HTML table, grid view controls and image control to Excel sheet.

Download the source code for more details.

This article will help explain the following points:

  1. Export HTML table content to Excel sheet.
  2. Export Grid View to Excel sheet.
  3. Export server-side controls and image to Excel sheet.

Also this article will help to sort the following issue.

  1. Control "GridView1" of type "GridView" must be placed inside a form tag with runat=server.
  2. RegisterForEventValidation can only be called during Render();

1. Export HTML table content to Excel sheet

I have created the following simple HTML table.



When I click on the export button, my exported Excel sheet will be:



Code

  1. Just create an HTML table and put that table in a div.
  2. Provide an Id to the div with runat=”server”.


     
  3. Provide this id in you C# code as in the following:


Note: If the table has a CSS class then that CSS class design will not be exported to the Excel sheet.

2. Export Grid View to Excel sheet

I have created the following simple Grandview.



When I click on the export button, I will get the following error.




To fix this error, add the following function.



Final output:



Code

  1. Just create a grid view and put that table in a div.
  2. Provide an Id to a div with runat=”server”.


     
  3. Provide this id in you C# code:


3. Export server-side controls and image to Excel sheet

I have created an image and a button and I need to export these to an Excel sheet.



When I click on the export button, I will get the following error:




To fix this error, add the following function:



When you click again on the export button, you will get the following error:




This error has occurred because of the “button” control. To fix this error, add the following attribute:



Final output:



Code:

  1. Just create a button and image controls and put that table in a div.
  2. Provide an Id to a div with runat=”server”.


     
  3. Provide this id in your C# code:


NOTE

  1. If the table has a CSS class then that CSS class design will not be exported to an Excel sheet.
  2. For an image to export you need to provide the main/original URL and not the http://localhot://
  3. You must create a HTML table to export an image or server-side controls.