自定义一个方法
private void Export(string FileType, string FileName)
{
Response.Charset = "GB2312";
Response.ContentEncoding = System.Text.Encoding.UTF7;
Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());
Response.ContentType = FileType;
this.EnableViewState = false;
StringWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
GridView1.RenderControl(hw);
Response.Write(tw.ToString());
Response.End();
}
导出按钮的单击事件
protected void Button1_Click(object sender, EventArgs e)
{
Export("application/ms-excel", "学生成绩报表.xls");
}
另外不可缺少的(如果没有下面方法会报错类型“GridView”的控件“GridView1”必须放在具有 runat=server 的窗体标记内)
public override void VerifyRenderingInServerForm(Control control)
{
}
记得引用命名空间IO、Text