禁用 GridView 中的分页到 Excel 导出

问题描述 投票:0回答:3

我有一个函数可以将一些数据从

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
,但页码在导出的文件中仍然可见。有人知道为什么吗?

c# asp.net gridview
3个回答
2
投票

要从 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


0
投票

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

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

0
投票

下面的代码块是可操作的。

screen output

GridView2.AllowPaging = false; GridView2.DataSource = GetProducts(); //Data Source GridView2.DataBind(); GridView2.RenderControl(htw);

© www.soinside.com 2019 - 2024. All rights reserved.