.NET DataGrid 导出Excel 无分页

 #region  导出Excel
    //
    protected void BtnExcelClick(object sender, EventArgs e)
    {

        ToExcel();

    }


    public void ToExcel()
    {

        Response.ContentType = "application/vnd.ms-excel";
        Response.Charset = "";
        Response.AddHeader("Content-Disposition",
                                    "attachment; filename=" + HttpUtility.UrlEncode("企业规模统计", Encoding.UTF8).ToString() +
                                    ".xls");
        this.EnableViewState = false;
        System.IO.StringWriter sw = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw);
        int nCur = dgList.CurrentPageIndex;
        int nSize = dgList.PageSize;
        dgList.AllowPaging = false;
        dgList.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(dgExport_ItemDataBound);
        dgList.CurrentPageIndex = 0;
        BindData();

        dgList.RenderControl(hw);

        //以下恢复分页
        dgList.AllowPaging = true;
        dgList.CurrentPageIndex = nCur;
        dgList.PageSize = nSize;
        BindData();
        string temp = sw.ToString().Replace("<br/>", "<br style=‘mso-data-placement:same-cell;‘/> ");
        temp = temp.Replace("border=\"0\"", "border=\"1\"");

        Response.Write(temp);
        Response.End();

    }
    protected static void dgExport_ItemDataBound(object sender, DataGridItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            foreach (TableCell cell in e.Item.Cells)
            {
                if (Regex.IsMatch(cell.Text.Trim(), @"^\d{12,}$") || Regex.IsMatch(cell.Text.Trim(), @"^\d+[-]\d+$"))
                {
                    cell.Attributes.Add("style", "vnd.ms-excel.numberformat:@");
                }
            }
        }
    }
    #endregion

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。