GridView 导出到Excel

 //导出到Excel文件    

protected void btnToExcel_Click(object sender, EventArgs e)

    {        

Response.Clear();        

//讲一个Http标头添加到输出流        

Response.AddHeader("content-disposition","attachment;filename=FileName.xls");        

//设置输出流的字符集        

Response.Charset = "utf-8";        

//设置Http MIME 类型        

Response.ContentType = "application/vnd.xls";     

//创建一个输出流        

StringWriter stringWrite = new StringWriter();        

HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);        

//写入到Excel 数据不分页        

GridView1.AllowPaging = false;        

//将服务器控件内容输出到所提供的HtmlWrite中        

GridView1.RenderControl(htmlWrite);        

//向客户端写入数据        

Response.Write(stringWrite.ToString());        

Response.End();

GridView1.AllowPaging = true;        

//加载GridView

initData(null, null, null, null, null, null);    

}

原文地址:https://www.cnblogs.com/huanhuan86/p/2771233.html