前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >使用RenderControl方法把GridView控件导出到EXCEL

使用RenderControl方法把GridView控件导出到EXCEL

作者头像
全栈程序员站长
发布2022-09-09 09:39:34
3810
发布2022-09-09 09:39:34
举报
文章被收录于专栏:全栈程序员必看

大家好,又见面了,我是你们的朋友全栈君。

// 把GridView输出到Excel文件 private void ExportExcel(GridView gridView, string title, string title2, string fileName) { int nHideCols = 0; //如果不想输出出某列,将Visible设为false即可 for (int i = 0; i < gridView.Columns.Count; i++) { if (gridView.Columns[i].HeaderText == “设备状态”) { gridView.Columns[i].Visible = false; gridView.Columns[i].ControlStyle.Width = 0; nHideCols = 1; break; } } //设定显示字符集 Response.Charset = “utf-8”; //设定内容字符集 Response.ContentEncoding = Encoding.GetEncoding(“utf-8”);

Asp.net中Response.Charset 与Response.ContentEncoding区别

//设定文件名 Response.AppendHeader(“Content-Disposition”, “attachment;filename=” + HttpUtility.UrlEncode(fileName, Encoding.UTF8).Replace(‘+’, ‘_’).Replace(‘-‘, ‘_’)); //设定文件类型 也可以是application/ms-word,也可以是text/html(字符集设为gb2312) Response.ContentType = “application/ms-excel”; this.EnableViewState = false; using (StringWriter tw = new StringWriter()) {

using (HtmlTextWriter hell = new HtmlTextWriter(tw)) { gridView.AllowPaging = false; gridView.RenderControl(hell);

string s = tw.ToString(); s = s.Replace(“\r\n”, “”); int index = s.IndexOf(“<tr”); //可以自定义Excel文件的标题 string head = “<tr><td colspan=\”” + (gridView.Columns.Count – nHideCols).ToString() + “\” style=\”text-align: center; height: 42px; font-size: 24px; font-weight: bolder; color: #000000;\”>” + title + “</td></tr>” + “<tr><td colspan=\”” + (gridView.Columns.Count – nHideCols).ToString() + “\” style=\”text-align: center; height: 24px; font-size: 12px; color: #000000;\”>” + title2 + “</td></tr>”; //使用Index来判断是否存在数据,当然也可以用gridView.Rows.Count来判断 if (index != -1) { //有数据的 s = s.Insert(index, head); } else { //没有数据的时候 s = “<table cellspacing=\”0\” cellpadding=\”3\” rules=\”rows\” border=\”1\” id=\”” + gridView.ID + “\” style=\”background-color:White;border-color:#E7E7FF;border-width:1px;border-style:None;border-collapse:collapse;\”>” + head + “</table>”; } Response.Write(s); Response.End(); } } }

//同时vs2005,vs2003会报错“类型“ExGridView”的控件“GridViewMaster”必须放在具有 runat=server 的窗体标记内 //需要添加下面取消对GridViewMaster 控件验证的方法 public override void VerifyRenderingInServerForm(Control control) { if (!control.GetType().Equals(gridView.GetType())) { base.VerifyRenderingInServerForm(control); } }

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/162030.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档