Search code examples
c#gridviewexportexport-to-excelxls

Why does my export to excel function export the whole page?


I'm trying to export a gridview that shows up in an window (modal) but it exports the whole page.

public void ExportToXLS(GridView gv)
{
    gv.AllowPaging = false;
    HttpContext.Current.Response.Buffer = true;
    HttpContext.Current.Response.ClearContent();
    HttpContext.Current.Response.ClearHeaders();
    HttpContext.Current.Response.Clear();
    HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=GridView.xls");
    HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
    System.IO.StringWriter stringWrite = new System.IO.StringWriter();
    System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
    GridView gvExp = new GridView();
    gvExp = gv;
    gvExp.RenderControl(htmlWrite);
    HttpContext.Current.Response.Write(stringWrite.ToString());
    HttpContext.Current.Response.Flush();
    HttpContext.Current.Response.Close();
    HttpContext.Current.Response.End();
}

Solution

  • The problem was i had a link button in the gridview and it was causing the page to not render properly.

    The solution was simple, i just removed the columns where the link buttons were considering that i really didn't need them.

    public void ExportToXLS(GridView gv)
    {
    
        GV.Columns[4].Visible = false;
        GV.Columns[5].Visible = false;
    
        gv.AllowPaging = false;
        HttpContext.Current.Response.Buffer = true;
        HttpContext.Current.Response.ClearContent();
        HttpContext.Current.Response.ClearHeaders();
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=GridView.xls");
        HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
        System.IO.StringWriter stringWrite = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
        GridView gvExp = new GridView();
        gvExp = gv;
        gvExp.RenderControl(htmlWrite);
        HttpContext.Current.Response.Write(stringWrite.ToString());
        HttpContext.Current.Response.Flush();
        HttpContext.Current.Response.Close();
        HttpContext.Current.Response.End();
    }
    

    The GV.Columns[ ].Visible = false; lines of code at the beginning just solved my whole problem.