首先在vs2005中创建一个web站点,在页面上拖拽一个gridview和sqldatasource控件,配置好sqldatasource并与gridview关联上。
在页面上在放一个button,button的单击事件中写下如下代码:
protected void Button1_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.Charset = "GB2312";
Response.AppendHeader("Content-Disposition", "attachment;filename=FileName.xls");
// 如果设置为 GetEncoding("GB2312");导出的文件将会出现乱码!!!
Response.ContentEncoding = System.Text.Encoding.UTF7;
Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
this.GridView1.RenderControl(oHtmlTextWriter);
Response.Output.Write(oStringWriter.ToString());
Response.Flush();
Response.End();
}
下面的这段代码也不能少,放在button单击事件的下面,
public override void VerifyRenderingInServerForm(Control control)
{
}
完成后运行程序,单击按钮就能将gridview中的数据导出到Excel中了。