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

Database, Information Technology

ASP.NET GridView Tutorial

301 Lessons

Export gridview to excel in asp.net – Part 57

The HTML and the code used in the demo, can be found at the link below.
http://csharp-video-tutorials.blogspot.com/2013/04/export-gridview-to-excel-in-aspnet-part.html

Link for csharp, asp.net, ado.net, dotnet basics and sql server video tutorial playlists
http://www.youtube.com/user/kudvenkat/playlists

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

Step 1: Create an asp.net 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.
ID=”btnExportToExcel”
Text=”Export to excel”
OnClick=”btnExportToExcel_Click”

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)
{
BindData();
}
}

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();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
}

protected void btnExportToExcel_Click(object sender, EventArgs e)
{
// Clear all content output from the buffer stream
Response.ClearContent();
// 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”;
}
}

GridView1.RenderControl(htw);
Response.Write(stringWriter.ToString());
Response.End();
}

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
http://support.microsoft.com/kb/948615

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 asp.net AccessDataSource in asp.net Alert another gridview ascending asp net gridview access database asp.net asp.net c# bind xml to gridview asp.net data source controls asp.net datagridview asp.net datasource controls asp.net get data from access database asp.net gridview asp.net gridview bind to xml asp.net gridview edit asp.net gridview formatting asp.net gridview sqldatasource asp.net gridview xml c# asp.net gridview xml file asp.net ms access database example asp.net objectdatasource explained between bi-directional bidirectional bind xml file to gridview in asp.net 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 c#.net 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 asp.net 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 asp.net 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 asp.net 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 asp.net objectdatasource objectdatasource in asp.net 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 asp.net 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 asp.net xslt basics xslt example xslt to transform xml to xml xslt transformation xslt transformation c# example