在GridView中禁用分页到Excel导出

时间:2016-02-25 12:10:02

标签: c# asp.net gridview

我有一个函数可以将一些数据从GridView导出到Excel,这些数据绑定到一些复选框。因此它只导出已检查的行。 这工作正常,但我似乎无法禁用导出分页? 这是我的代码:

 private void ExportGridToExcel()
{

    bool isSelected = false;
    foreach (GridViewRow i in GridView1.Rows)
    {
        CheckBox cb = (CheckBox)i.FindControl("chkSelect");
        if (cb != null && cb.Checked)
        {
            isSelected = true;
            break;
        }
    }

    if (isSelected)
    {
        GridView gvExport = GridView1;
        // this below line for not export checkbox to excel file
        gvExport.Columns[0].Visible = false;
        foreach (GridViewRow i in GridView1.Rows)
        {
            gvExport.Rows[i.RowIndex].Visible = false;
            CheckBox cb = (CheckBox)i.FindControl("chkSelect");
            if (cb != null && cb.Checked)
            {
                gvExport.Rows[i.RowIndex].Visible = true;
            }
        }

        Response.Clear();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", "attachment;filename=ExportGridData.xls");
        Response.Charset = "";
        Response.ContentType = "application/vnd.ms-excel";
        StringWriter sw = new StringWriter();
        HtmlTextWriter htW = new HtmlTextWriter(sw);
        Response.ContentEncoding = System.Text.Encoding.Unicode;
        Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        gvExport.AllowPaging = false;
        gvExport.RenderControl(htW);
        Response.Output.Write(sw.ToString());
        Response.End();

    }
}

protected void Button3_Click(object sender, EventArgs e)
{

    ExportGridToExcel();

}

如您所见,我已设置AllowPaging = false,但页码仍在导出的文件中可见。任何人都知道为什么?

2 个答案:

答案 0 :(得分:1)

要从GridView导出整个数据,您必须重新绑定数据源

//1.bind with paging disabled
gvExport.AllowPaging = false;
gvExport.DataBind();

//2.export method here

//3.bind with paging enabled
gvExport.AllowPaging = true;
gvExport.DataBind();

但如果有可能我会直接从数据源导出数据,因为您必须删除标题,隐藏列,替换 并单独处理asp:Checkbox等控件

如果您想从asop:GridView - http://forums.asp.net/post/4222334.aspx

导出,这是一种很好的方法

答案 1 :(得分:0)

在渲染之前 - 禁用分页,绑定数据然后渲染:

gvExport.AllowPaging = false;
gvExport.DataSource = ds; //Data Source
gvExport.DataBind();
gvExport.RenderControl(objHtmlTextWriter)