Explore the Experience in SharePoint 2013

Thursday, October 16, 2014

Export Grid View Data to Excel

No comments
private void ExportGriviewToExcel(System.
Web.UI.WebControls.GridView gvReport, string fileName)
        {
            try
            {
                DateTime dtCurrentdate = System.DateTime.Now;
                fileName = fileName + '-' + dtCurrentdate.Date.ToShortDateString();
                var attachment = "attachment; filename=" + fileName + ".xls"; //Setting the attachment name.
                HttpContext.Current.Response.ClearContent(); //clears all content output from the buffer stream.
                HttpContext.Current.Response.AddHeader("content-disposition", attachment);
                HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
                using (var sw = new StringWriter())
                {
                    using (var htw = new HtmlTextWriter(sw))
                    {
                        using (var frm = new HtmlForm())
                        {
                            gvReport.AllowPaging = false;
                            gvReport.DataSource = dtTAt;
                            gvReport.DataBind();
                            gvReport.Parent.Controls.Add(frm);
                            frm.Controls.Add(gvReport);
                            frm.RenderControl(htw);
                            HttpContext.Current.Response.Write(sw.ToString());
                            HttpContext.Current.Response.End();
                        }

                    }
                }

            }
            catch (Exception ex)
            {

               
            }
        }

No comments :

Post a Comment