Latest

Export gridview data to Excel document in asp.net C#


Follow the  steps involved :

Step 1: Create a aspx page with a grid view control.

 ViewExcelReport.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td align="right">
<asp:ImageButton ID="btnExcel" runat="server"   onclick="btnExcel_Click" />
</td>
</tr>
<tr>
<td>
<asp:GridView runat="server" ID="gridview1   DataSourceID="databasedetails"  AllowPaging="true" AllowSorting="true" AutoGenerateColumns="false">
<RowStyle BackColor="#EFF3FB" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField DataField="UserId" HeaderText="UserId" />
<asp:BoundField DataField="UserName" HeaderText="UserName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="Location" HeaderText="Location" />
</Columns>
</asp:GridView>
</td>
</tr>
</table>
<asp:SqlDataSource ID="databasedetails" runat="server" ConnectionString="<%$ConnectionStrings:dbconnection %>"
SelectCommand="select * from Usertable"/>
</div>
</form>
</body>
</html>


Step 2:
Add the code for the button click in ViewExcelReport.aspx.cs


protected void btnExcel_Click_Click(object sender, ImageClickEventArgs e)
 
{
                      String strFileName="Excel";

             Response.Clear(); 


            Response.AddHeader("content-disposition",


            string.Format("attachment;filename={0}.xls", strFileName));


            Response.Charset = "";

            Response.ContentType = "application/vnd.xls";

            StringWriter stringWrite = new StringWriter();

            HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

            gridview.AllowPaging = false;

            BindSGrid();

            gridview.RenderControl(htmlWrite);

            Response.Write(stringWrite.ToString());

            Response.End();

            gridview.AllowPaging = true;

            BindGrid();

}
  
public override void VerifyRenderingInServerForm(Control control)
{
/* Confirms that an HtmlForm control is rendered for the specified ASP.NET
server control at run time. */
}


 


Now you are done , you can export the grid view in to Excel format.


if you’re getting any error message like 

RegisterForEventValidation can only be called during Render();

To solve, add the overriding function VerifyRenderingInServerForm event in code. 



Thanks for reading this article ! ! please leave your comments and suggestion about this article.
Thank you.
ramdsr26

Protected by Copyscape DMCA Copyright Protection

No comments