Export gridview to excel in asp.net – Part 5704:33

  • 0
Published on November 24, 2017

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

Link for csharp, asp.net, ado.net, dotnet basics and sql server video tutorial 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

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”;

Enjoyed this video?
"No Thanks. Please Close This Box!"