GridView的操作:导出Excel[方案一]
GridView的操作:从GridView导出数据到Excel
方案一:简单可行的方法
并且数据量不能超过65535,
方案一:简单可行的方法
1protected void WriteExcel_Btn_Click(object sender, EventArgs e)
2{
3HttpContext curContext = System.Web.HttpContext.Current;
4StringWriter strWriter = new StringWriter();
5HtmlTextWriter htmlWriter = new HtmlTextWriter(strWriter);
6//ContentType可以在注册表中对应的文件类型中找到
9curContext.Response.Charset = "GB2312";
10
11GridView GV = new GridView();
12//DT是用于显示的那个GridView的数据源
13//也可以写:GV.DataSource=GridView1.DataSource;
14//GridView1是用于显示的GridView
15GV.DataSource = DT;
16GV.AllowPaging = false;
17GV.DataBind();
18GV.RenderControl(htmlWriter);
19curContext.Response.Write(strWriter.ToString());
20curContext.Response.End();
21}
这个方案的缺点是,只能向Excel文件中写入一个WorkSheet,2{
3HttpContext curContext = System.Web.HttpContext.Current;
4StringWriter strWriter = new StringWriter();
5HtmlTextWriter htmlWriter = new HtmlTextWriter(strWriter);
6//ContentType可以在注册表中对应的文件类型中找到
7curContext.Response.ContentType = "application/vnd.ms-excel";
8curContext.Response.ContentEncoding = Encoding.GetEncoding("GB2312");9curContext.Response.Charset = "GB2312";
10
11GridView GV = new GridView();
12//DT是用于显示的那个GridView的数据源
13//也可以写:GV.DataSource=GridView1.DataSource;
14//GridView1是用于显示的GridView
15GV.DataSource = DT;
16GV.AllowPaging = false;
17GV.DataBind();
18GV.RenderControl(htmlWriter);
19curContext.Response.Write(strWriter.ToString());
20curContext.Response.End();
21}
并且数据量不能超过65535,
对于小数据量是适合的
补充:给文件添加名字
curContext.Response.AddHeader("Content-Disposition",
"attachment;filename=" + HttpUtility.UrlEncode("属性-属性值对应表.xls"));
"attachment;filename=" + HttpUtility.UrlEncode("属性-属性值对应表.xls"));