Exporting Grid View to Excel in SharePoint 2010

1 comment
Hi All,

The following post will explain about the how to export grid view data to excel.



Protected void btnExportExcel(object sender,EventArgs e)
{
//Calling a method which will do the business requirement(export excel)
      Export To Excel()
}

public void ExportToExcel()
        {
            string attachment = string.Empty;
           attachment = "attachment; filename=ReportName" + ".xls"; //Setting the attachment name.
            Response.ClearContent();//clears all content output from the buffer stream.
            Response.AddHeader("content-disposition", attachment);
          
            Response.ContentType ="application/vnd.ms-excel";
            StringWriter sw = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            HtmlForm frm = new HtmlForm();
            htw.WriteLine("<center><b><u><font size='5'> " +ReportName + " </font></u></b></center>");//will be displayed in excel as a heading.
            GridView1.Parent.Controls.Add(frm);           
            frm.Controls.Add(GridView1);
            frm.RenderControl(htw);
            Response.Write(sw.ToString());
            Response.Flush();
            Response.End();
        }
 

Related Post

1 comment:

  1. Still getting the "RegisterForEventValidation can only be called during Render();" error. Any idea how to solve this?

    ReplyDelete