您的位置:首页 > 数据库

Gradview绑定数据库数据并导出Excel

2009-08-31 08:48 363 查看
Code
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)
{
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: