ASP.NET GridView Tutorial - Export gridview to excel in – Part 57

Database, Information Technology

ASP.NET GridView Tutorial

301 Lessons

Export gridview to excel in – Part 57

The HTML and the code used in the demo, can be found at the link below.

Link for csharp,,, dotnet basics and sql server video tutorial playlists

In this video, we will discuss about exporting gridview data to excel.

Step 1: Create an web application project.

Step 2: Drag and drop a gridview control and a button control on webform1.aspx. Autoformat the gridview control to use “BrownSugar” scheme. Set the following properties of the button control.
Text=”Export to excel”

Step 3: Copy and paste the following code in webform1.aspx.cs. The code is well commented and is self-explanatory.
protected void Page_Load(object sender, EventArgs e)
if (!IsPostBack)

private void BindData()
string CS = ConfigurationManager.ConnectionStrings[“DBCS”].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
SqlDataAdapter da = new SqlDataAdapter(“Select * from tblEmployee”, con);
DataSet ds = new DataSet();
GridView1.DataSource = ds;

protected void btnExportToExcel_Click(object sender, EventArgs e)
// Clear all content output from the buffer stream
// Specify the default file name using “content-disposition” RESPONSE header
Response.AppendHeader(“content-disposition”, “attachment; filename=Employees.xls”);
// Set excel as the HTTP MIME type
Response.ContentType = “application/excel”;
// Create an instance of stringWriter for writing information to a string
System.IO.StringWriter stringWriter = new System.IO.StringWriter();
// Create an instance of HtmlTextWriter class for writing markup
// characters and text to an ASP.NET server control output stream
HtmlTextWriter htw = new HtmlTextWriter(stringWriter);

// Set white color as the background color for gridview header row
GridView1.HeaderRow.Style.Add(“background-color”, “#FFFFFF”);

// Set background color of each cell of GridView1 header row
foreach (TableCell tableCell in GridView1.HeaderRow.Cells)
tableCell.Style[“background-color”] = “#A55129”;

// Set background color of each cell of each data row of GridView1
foreach (GridViewRow gridViewRow in GridView1.Rows)
gridViewRow.BackColor = System.Drawing.Color.White;
foreach (TableCell gridViewRowTableCell in gridViewRow.Cells)
gridViewRowTableCell.Style[“background-color”] = “#FFF7E7”;


Step 4: Run the application and click on “Export to excel” button. You will get an error stating – Control ‘GridView1’ of type ‘GridView’ must be placed inside a form tag with runat=server. This is because, we are calling GridView1.RenderControl(htmlTextWriter) method. This causes .net to think that a Server-Control is being rendered outside of a Form. To fix this error, we need to override VerifyRenderingInServerForm() method. Copy and paste the following method in webform1.aspx.cs.
public override void VerifyRenderingInServerForm(Control control)

At this point, run the application and click on “Export to excel button. The data gets exported to excel as expected. However, when you try to open the file you will get a warning message stating – The file you are trying to open, ‘Employee.xls’, is in a different format than specified by the file extension. Verify that the file is not corrupted and is from a trusted source before opening the file. Do you want to open the file now?

According to MSDN – The warning message is a user-notification function that was added to Excel 2007. The warning message can help prevent unexpected problems that might occur because of possible incompatibility between the actual content of the file and the file name extension.

One way to resolve this error, is to edit the registry. Microsoft knowledge base article related to this error

If you want to export the same data to microsoft word, there are only 2 changes that you need to do.
First Change: Change the file extension to “.doc” instead of “.xls”
Response.AppendHeader(“content-disposition”, “attachment; filename=Employees.doc”);

Second Change: Set the content type to word
Response.ContentType = “application/word”;

    Access DataSource in AccessDataSource in Alert another gridview ascending asp net gridview access database c# bind xml to gridview data source controls datagridview datasource controls get data from access database gridview gridview bind to xml gridview edit gridview formatting gridview sqldatasource gridview xml c# gridview xml file ms access database example objectdatasource explained between bi-directional bidirectional bind xml file to gridview in binding xml file to gridview business objects C# c# accessdatasource c# data source object c# datagrid example c# get data from access database c# gridview sqldatasource c# sql data source connection string c# sqldatasource example c# sqldatasource selectcommand c# xslt example c# xslt transform xml document c# xslt tutorial cells changing data checkbox client-side code colspan CompareAllValues compute concurrency confirm ConflictDetection conflictdetection property content control controls convert xml node to attribute custom paging Data DataFormat String DataFormatString datagrid in datagrid in c# DataKeyNames dataset datasource datasource controls default paging delete delete confirmation delete data Deleting deleting data descending detailed data details view details view in DetailsView difference display Displaying displaying gridview document Drill Down Drilldown drilling down dropdownlist edit edit and update editing EmptyDataTemplate EmptyDataText event example Excel Export exporting footer footer row format formatting gridview at runtime Formatting gridview in code generate Grid View gridview gridview currency format gridview datasource xml file gridview date format gridview ms access database gridview retrieve templatefield value gridview RowDataBound gridview template gridview templatefield gridview templatefield get control GridViewDeletedEventArgs hierarchical data how how to display date in gridview without time How to get value from TemplateField in GridView how to pass data from gridview to another page in image field imagefield images implement implementing insert inside javascript jquery KeepInEditMode Merging. merge microsoft multiple rows nested nested gridview nesting no data no rows in datasource object datasource object datasource in objectdatasource objectdatasource in order OverwriteChanges page page numbers page size paging pdf properties read xml file with child nodes c# Repeater Retrieve ItemTemplate control value in Gridview row cells rowcommand rowdatabound rowdatabound event RowDataBound example RowDeleted event RowUpdated several rows show date only in gridview showing sort sort arrows sort images sortable Sorting sqldatasource sqldatasource in stored procedures summary data templatefield totals tutorial two or more rows Update update data Updated updating updating data Use use optimistic concurrency using validation Validation Controls web server when without without data source controls without datasource controls Word workbook working with xmldatasource in xslt basics xslt example xslt to transform xml to xml xslt transformation xslt transformation c# example