asp.net 禁用GridView到Excel导出中的分页

lb3vh1jj  于 2023-03-09  发布在  .NET
关注(0)|答案(3)|浏览(145)

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

1mrurvl1

1mrurvl11#

要从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导出,这是一种很好的方法

rnmwe5a2

rnmwe5a22#

呈现前-禁用分页,绑定数据,然后呈现:

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

3lxsmp7m3#

下面的代码块是可操作的。
screen output x1月1x

相关问题