码迷,mamicode.com
首页 > 其他好文 > 详细

GridView内容导出Excel文件

时间:2014-10-06 17:28:50      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:io   os   ar   for   文件   数据   sp   c   on   

首先,将数据库中的内容绑定到GridView中,这个方法随意,这里采用ADO.NET实现。

protected void Page_Load(object sender, EventArgs e)
{

SqlDataAdapter sda = new SqlDataAdapter("select * from tb_StuResult", sqlcon);
DataSet ds = new DataSet();
sqlcon.Open();
sda.Fill(ds);
sqlcon.Close();
GridView1.DataSource = ds;
GridView1.DataBind();

}

添加一个ASP按钮。按钮代码:

protected void Button1_Click(object sender, EventArgs e)
{
OutExcel(this.GridView1);
}

编写OutExcel函数:

private void OutExcel(GridView gv)
{
Response.Clear();
Response.ClearContent();
Response.AddHeader("Content-Disposition", "attachment;filename=" + DateTime.Now.ToString("_yyMMdd") + ".xls");
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gv.RenderControl(htw);
Response.Write(sw.ToString());
Response.Flush();
Response.End();

}

如果要把GridView内容输出Excel的话,必须重写VerifyRenderingInServerForm,否则会提示GridView必须runat server;

重写代码:

    public override void VerifyRenderingInServerForm(Control control){//这里面不需要任何代码; }

GridView内容导出Excel文件

标签:io   os   ar   for   文件   数据   sp   c   on   

原文地址:http://www.cnblogs.com/hbhssm/p/4008273.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!