Wednesday, April 6, 2011

Export to Excel directly from grid

code for export data in excel from Gridview directly with header

protected void BindToExcel()
{

//Please check AutoEventWireup="true" EnableEventValidation="false" and VerifyRenderingInServerForm(Control control)
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
//Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=Client.xls");
Response.Charset = "";
this.EnableViewState = false;

StringWriter sw = new StringWriter();
StringWriter headWrite = new StringWriter();

HtmlTextWriter htw = new HtmlTextWriter(sw);

//Make some colum visible/not visible
dgDetailsTicketStatus.Columns[7].Visible = false;
dgDetailsTicketStatus.Columns[8].Visible = true;
dgDetailsTicketStatus.RenderControl(htw);

//Add Excel Report header
//Write "Details Report" in table tag.
headWrite.Write("Details Report");
headWrite.WriteLine(sw);

Response.Write(headWrite.ToString());
Response.End();
}

protected void btnExportToExcel_Click(object sender, EventArgs e)
{
BindToExcel();
}

public override void VerifyRenderingInServerForm(Control control)
{
}

No comments: