Hi.
Here I would like to share a code to export gridview data to
excel File. I hope it is useful to understand the concept behind on export grid
view data.
When export gridview data you need to use one button to do
the action of exporting.
We need to write the code on button event……
protected void
Button1_Click(object sender, EventArgs e)
{
//***we need
to set as paging as false to export all the data from the gridview.
GridView1.AllowPaging = false;
//***Again
bind the data into gridview
bindgrid();
//***Function
for to export the data...
ExportExcel("File1.xls", GridView1);
}
|
Here the method for export excels method function………
public static void
ExportExcel(string fileName, GridView gv)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader(
"content-disposition", string.Format("attachment; filename={0}", fileName));
HttpContext.Current.Response.ContentType = "application/ms-excel";
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
// Create a form to contain the
grid
Table
table = new Table();
// add the header row to the
table
if
(gv.HeaderRow != null)
{
table.Rows.Add(gv.HeaderRow);
}
// add each of the data rows to
the table
foreach (GridViewRow
row in gv.Rows)
{
table.Rows.Add(row);
}
// add the footer row to the
table
if
(gv.FooterRow != null)
{
table.Rows.Add(gv.FooterRow);
}
// render the table into the
htmlwriter
table.RenderControl(htw);
// render the htmlwriter into the
response
HttpContext.Current.Response.Write(sw.ToString());
HttpContext.Current.Response.End();
}
}
}
|
I hope you like this article to export the gridview data to
excel file ..
Post your comment …
0 comments:
Post a Comment