富贵资源网 Design By www.hznty.com

本文实例讲述了asp.net实现Gradview绑定数据库数据并导出Excel的方法。分享给大家供大家参考,具体如下:

protected void showData_Click(object sender, EventArgs e)
{
  SqlConnection myConnection
   = new SqlConnection("Data Source=localhost;Initial Catalog=test;User ID=sa;password=sa");
  SqlDataAdapter ad = new SqlDataAdapter("SELECT * FROM booklist", myConnection);
  DataSet ds = new DataSet();
  ad.Fill(ds);
  this.gvShowData.DataSource = ds;
  this.gvShowData.DataBind();
}
//导出Excel表
protected void btnExportToExcel_Click(object sender, EventArgs e)
{
  Response.Charset = "GB2312";
  Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
  Response.AddHeader("Content-Type", "application/vnd.ms-excel");
  Response.AddHeader("Content-Disposition", "myexcelfile.xls");
  //以此编码模式导出才不会出现乱码
  StringWriter sw = new StringWriter();
  HtmlTextWriter htw = new HtmlTextWriter(sw);
  gvShowData.RenderControl(htw);
  Response.Write(sw.ToString());
  Response.End();
}
//一定要写,否则出错!!
public override void VerifyRenderingInServerForm(Control control)
{
}

希望本文所述对大家asp.net程序设计有所帮助。

富贵资源网 Design By www.hznty.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
富贵资源网 Design By www.hznty.com