如何将Gridview行导出到Excel工作表?

时间:2014-03-08 17:53:54

标签: c# asp.net excel

  

我的任务是将 gridview 导出到Excel工作表,因为我可以导出   当前页面或前100行或所有页面。与当前页面配合良好   页面,但其他人不起作用

 protected void btnExportGrid_Click(object sender, ImageClickEventArgs e)
{
    Table table = new Table
    {
        GridLines = this.Data.GridLines
    };
    if (this.rdoBtnListExportOptions.SelectedIndex == 1)
    {
        this.Data.AllowPaging = false;
        this.Data.DataBind();
        GridViewExportUtil.Export("Customers.xls", this.Data);
    }
    else if (this.rdoBtnListExportOptions.SelectedIndex == 2)
    {
        this.Data.PageSize = 50;
        this.Data.DataBind();
        GridViewExportUtil.Export("Customers.xls", this.Data);
    }
    else
    { GridViewExportUtil.Export("Customers.xls", this.Data); }
}

1 个答案:

答案 0 :(得分:0)

试试这个,它适用于ASP.NET

        Response.Clear();
        Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");
        Response.ContentType = "application/ms-excel";
        Response.ContentEncoding = System.Text.Encoding.Unicode;
        Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());

        System.IO.StringWriter sw = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(sw);

        gridview.RenderControl(hw);

        Response.Write(sw.ToString());
        Response.End();