为什么我的 export to excel 函数会导出整个页面?

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

我正在尝试导出显示在 window(模态)中的 gridview,但它会导出整个页面。

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();
}

问题是我在 gridview 中有一个 link 按钮,它导致页面无法正确呈现。

解决方案很简单,我只是删除了 link 按钮所在的列,因为我确实不需要它们。

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();
}

开头的GV.Columns[ ].Visible = false;行代码正好解决了我的全部问题。