GridView导出成Excel(整理)

来源:互联网 发布:阿里云 弹性ip bgp带宽 编辑:程序博客网 时间:2024/06/04 17:39

将gridview导出成excel

后台代码:

 #region 导入Excel
    protected void btnOutExcel_Click(object sender, EventArgs e)
    {
        string style = "<style> td { mso-number-format:\"\\@\"; } </style> ";//导入excel时,将所有数据类型改为文本类型

        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.Buffer = true;
        HttpContext.Current.Response.Charset = "UTF-8";
        HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=TerminalDetails.xls");


        Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
        HttpContext.Current.Response.ContentType = "application/ms-excel";
        Response.Write("<meta http-equiv=Content-Type content=\"text/html;chartset=UTF-8\">");
        System.IO.StringWriter stringWrite = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

        this.gdvTerminalDetals.AllowPaging = false;
        stringWrite.WriteLine(style);
        this.gdvTerminalDetals.RenderControl(htmlWrite);

        Response.Output.Write(stringWrite.ToString());
        HttpContext.Current.Response.Flush();
        HttpContext.Current.Response.End();
    }


    public override void VerifyRenderingInServerForm(Control control)
    {

    }
    #endregion