Hello all,
In asp.net we show our database records in tabular format using GridView control and to export that GridView Data to excel, we can use following code packet.
protected void gridViewExportToExcel()
{
if (GridView.Rows.Count > 0)
{
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=ExporttoExcel.xls");
Response.Charset = string.Empty;
Response.Cache.SetCacheability(System.Web.HttpCacheability.Public);
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
Table table = new Table();
table.GridLines = GridView.GridLines;
table.Rows.Add(GridView.HeaderRow);
for (int i = 0; i < GridView.Rows.Count; i++)
{
GridViewRow row = GridView.Rows[i];
//Apply text style to each Row
row.Attributes.Add("class", "textmode");
table.Rows.Add(row);
}
table.RenderControl(hw);
string style = @"";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
else
{
string script = "<script language="javascript"> alert('No data to export');";
ScriptManager.RegisterStartupScript(Page, this.GetType(), "Alert Message", script, false);
}
}
0 Comment(s)