首先,将数据库中的内容绑定到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){//这里面不需要任何代码; }