从Gridview 中导出数据到EXCEL

前端:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" EnableEventValidation="false" %>

<asp:GridView ID="gv_Score" runat="server" CellPadding="4" ForeColor="#333333" AllowPaging="false">

再定义一个按钮,实现导出功能。

后台CS:

using System.IO;

 protected void btn_Export_Click(object sender, EventArgs e)  

   {        

      Response.Charset="GB2312"; 

      Response.ContentEncoding=System.Text.Encoding.UTF8;

      Response.AddHeader("Content-Disposition","attachment;FileName="+HttpUtility.UrlEncode(DateTime.Now.ToString(),System.Text.Encoding.UTF8)+".xls");

     Response.ContentType = "application/ms-excel"; //输出文件类型为excel类型

     this.EnableViewState = false; 

     StringWriter wt = new StringWriter();  

      HtmlTextWriter hw = new HtmlTextWriter(wt);

       gv_Score.RenderControl(hw);      

    Response.Write(wt.ToString());     

    Response.End();    

}    

//必须覆写些方法,不然会报错。

public override void VerifyRenderingInServerForm(Control control)   

  {

    }

posted on 2013-05-14 22:59  众里寻他千万度  阅读(171)  评论(0编辑  收藏  举报

导航