代码改变世界

asp.net的GridView导出到Excel

2012-04-22 15:23  追梦网络  阅读(273)  评论(0编辑  收藏  举报

 protected void btnExcel_Click(object sender, EventArgs e)
        {
            string orderNumber = (Convert.ToInt64(DateTime.Now.ToString("yyyyMMddhhmmss"))).ToString();
            Response.Clear();
            Response.BufferOutput = true;
            //设定输出的字符集
            Response.Charset = "GBK";
            //假定导出的文件名为FileName.xls
            Response.AppendHeader("Content-Disposition", "attachment;filename=User_" + orderNumber + ".xls");
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("GBK");
            //设置导出文件的格式
            Response.ContentType = "application/ms-excel";
            //关闭ViewState
            EnableViewState = false;
            System.Globalization.CultureInfo cultureInfo = new System.Globalization.CultureInfo("ZH-CN", true);
            System.IO.StringWriter stringWriter = new System.IO.StringWriter(cultureInfo);
            System.Web.UI.HtmlTextWriter textWriter = new System.Web.UI.HtmlTextWriter(stringWriter);
            gridTrade.BackColor = Color.FromArgb(255, 255, 255);
            //gridTrade.Columns[9].Visible = false;
            gridTrade.RenderControl(textWriter);
            //把HTML写回浏览器
            Response.Write(stringWriter.ToString());
            Response.End();
        }
        public override void VerifyRenderingInServerForm(Control control)
        {

        }