一个控件 datagrid1
自定义一个方法BindDataGrid() 用于绑定数据.
顺便说一下,不支持datagrid有 添加 编辑 删除 按钮. 但只要保证导出时没有即可,我就是导出时,先取消按钮再导的.去掉编辑删除按钮,用了个笨方法,导出的时候直接隐藏了前两列,"this.DataGrid1.Columns[0].Visible = false",然后即可顺利导出.
省略其它代码,导出方法如下:
1,datagrid无分页
Response.ContentEncoding =
// 有时用 gb2312 不能正常显示中文,要用 utf-8
System.Text.Encoding.GetEncoding("gb2312");
Response.AppendHeader("Content-Disposition", "attachment;filename=" + "result.xls"); //必要,做成下载文件
//如果要直接在浏览器中打开,把上行注释掉,换成下面这行
//Response.ContentType = "application/vnd.ms-excel";
Response.Charset = ""; // 从Content-Type header中去除charset设置
//关闭 ViewState
this.EnableViewState = false ;
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(tw);
//获取control的HTML
this.DataGrid1.RenderControl(hw);
//把HTML写回浏览器
Response.Write(tw.ToString());
Response.End();
2,datagrid分页
只需在以上代码前后加入:
this.DataGrid1.AllowPaging = false;
BindDataGrid(); //导出方法不支持分页,将分页取消,数据重新导入datagrid
...
this.DataGrid1.AllowPaging = true; //恢复分页
浙公网安备 33010602011771号