How to export datagrid to excel


In this article I am going to explain how you could export the grid view content into the excel sheet.i bind the grid view content in dynamically. here i put the design code and server side code also.

Learn how to export the grid view contents into the excel sheet

the .aspx page have a grid view and button control for export option.the web page/ design content is,


<div align="center">
<asp:GridView ID="grid_mrs" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None">
<AlternatingRowStyle BackColor="White" />
<EditRowStyle BackColor="#2461BF" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#EFF3FB" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F5F7FB" />
<SortedAscendingHeaderStyle BackColor="#6D95E1" />
<SortedDescendingCellStyle BackColor="#E9EBEF" />
<SortedDescendingHeaderStyle BackColor="#4870BE" />
</asp:GridView>
<br />
<asp:Button ID="bt_export" runat="server" Text="Export Excel" OnClick="bt_export_Click" />
</div>


this code is the server side,


//the page event have to fill the grid content.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
fill_grid_details();
}
}


private void fill_grid_details()
{
try
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MMConnectionString"].ConnectionString);
con.Open();
SqlDataAdapter da = new SqlDataAdapter("select * from tl_mrs_new", con);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
grid_mrs.DataSource = ds;
grid_mrs.DataBind();
}
catch (Exception ex) { lblMessage.Text = ex.ToString(); }
}

//this event is to generate the grid view content to excel sheet,

protected void bt_export_Click(object sender, EventArgs e)
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=GridView1.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.xls";
StringWriter SWriter = new System.IO.StringWriter();
HtmlTextWriter HTWriter = new HtmlTextWriter(SWriter);
grid_mrs.RenderControl(HTWriter);
Response.Write(SWriter.ToString().Trim());
Response.End();
}


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: