Wednesday, 23 January 2013 13:55

how to export GridView items to excel with header information

Written by 
Rate this item
(0 votes)

Asp.net makes it easy to export tabular data to excel file.It's
easier to use GridView control data to export to excel.the following
codes shows how u can achieve this along with some header info at the
top of the data rows in excel -

here i populated data in the dynamically created gridview first.you
can use the gridview rendered in the page before.

List<int> bidIds = new List<int>();
List<ExportBidGc> pBidList = new List<ExportBidGc>();
///////////// pBidList needs to be populated with data//////////////

GridView Grid1 = new GridView();
Grid1.DataSource = pBidList; //now set datasource as pBidList
Grid1.DataBind();
Label info = new Label();
info.Text = "<span style='background-color:Yellow'>Project Name: "
+ proNameLabel.Text + "<br/>" + proComNameLabel.Text <br/></span>";

Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "Attachment;filename=Bids.xls");
Response.Charset = "";

this.EnableViewState = false;
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
info.RenderControl(oHtmlTextWriter);
Grid1.RenderControl(oHtmlTextWriter);

Response.Write(oStringWriter.ToString());

Response.End();

hope it helped u a lot.

Read 4031 times
Super User

Email This email address is being protected from spambots. You need JavaScript enabled to view it.

Latest discussions

  • No posts to display.