沃德软件技术资讯频道

传递网站建设与软件开发资讯

C#\JAVA\IOS\Android等技术研究

Ajax+DIV+CSS技术技巧/HTML5研究

视觉设计、软件体验度与流行趋势

沃德软件团队经验与心得体会分享

门户网站设计有很多种。最为国人熟知的是像迅雷看看、新浪、腾讯网那种信息类门户。现在也有博客门户等。...[详细]
SQLSERVER

asp.net实现Gradview绑定数据库数据并导出Excel的方法

发布:昆明沃德软件 发布时间:2015-11-29  浏览次数:1693
更多

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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)
{
}