asp.net – 如何在excel中导出网格视图时跳过某些列?
发布时间:2020-12-16 06:59:01 所属栏目:asp.Net 来源:网络整理
导读:我有一个网格视图.其中包含一些列.假设它有10列,只有8列有标题而2列标题为空.现在我将此gridview导出到excel,其中包含所有10列,其中2列没有名称.如何在将GridView导出到excel时排除这2个空标题列.我使用以下代码: protected void btnExportToExcel_Click(ob
|
我有一个网格视图.其中包含一些列.假设它有10列,只有8列有标题而2列标题为空.现在我将此gridview导出到excel,其中包含所有10列,其中2列没有名称.如何在将GridView导出到excel时排除这2个空标题列.我使用以下代码:
protected void btnExportToExcel_Click(object sender,EventArgs e)
{
Export("Customers.xls",this.gdvMessages);
}
private void Export(string fileName,GridView gv)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader(
"content-disposition",string.Format("attachment; filename={0}",fileName));
HttpContext.Current.Response.ContentType = "application/ms-excel";
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
// Create a form to contain the grid
Table table = new Table();
// add the header row to the table
if (gv.HeaderRow != null)
{
PrepareControlForExport(gv.HeaderRow);
table.Rows.Add(gv.HeaderRow);
}
// add each of the data rows to the table
foreach (GridViewRow row in gv.Rows)
{
PrepareControlForExport(row);
table.Rows.Add(row);
}
// add the footer row to the table
if (gv.FooterRow != null)
{
PrepareControlForExport(gv.FooterRow);
table.Rows.Add(gv.FooterRow);
}
// render the table into the htmlwriter
table.RenderControl(htw);
// render the htmlwriter into the response
HttpContext.Current.Response.Write(sw.ToString());
HttpContext.Current.Response.End();
}
}
}
解决方法
如果您不需要它们,您可能不会在HTML表格中包含这两列……或者当用户按“导出到Excel”按钮而不包括列时,您可以重新编写表格.您还可以将表加上另一个带有隐藏列的表,并在用户单击“导出到Excel”按钮时从中获取数据.此外,您根本无法显示数据,当用户加载页面时,或单击按钮下载没有列的数据.祝好运!
已编辑:对于此独有方案,您可能希望以下列方式编辑代码: // add the header row to the table
if (gv.HeaderRow != null)
{
TableRow tr = new TableRow();
foreach (DataControlFieldHeaderCell c in gv.HeaderRow.Cells)
{
if (c.Text != " ") {
tr.Cells.Add(new TableCell() { Text = c.Text});
}
}
PrepareControlForExport(tr);
table.Rows.Add(tr);
}
代码的这一部分是循环遍历标题行中的每个单元格,如果它是空的,则不包括它.然后将其添加到html表中.如果需要,可以调整此值,以便表的其余部分添加这些列所属的单元格.如果这不是您所需要的,那么您可能需要使用实际Gridview和所需输出的几个屏幕截图. 祝好运! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- 在ASP.NET 5响应中设置Content-Length标头
- asp.net – visual studio 2017调试无法启动程序无效指针
- asp.net-mvc – 如何在ASP MVC中编码完整的URL字符串
- asp.net-mvc – 输入类型=“隐藏”vs htmlhelper奇怪的问题
- asp.net – 覆盖webapi odata链接的主机
- asp.net – 如何接收JSON作为MVC 5操作方法参数
- asp.net-mvc – 如何使输入字段仅允许使用EF和数据注释的数
- asp.net – 将Eval参数从ASPX文件传递给JavaScript函数
- asp.net – 嵌套的用户控件的控件为null
- asp.net-mvc – MVC包含路径无效错误
推荐文章
站长推荐
- 将.net核心连接到SSAS
- asp.net – 如何跟踪IIS服务器性能
- asp.net-mvc – 使用部分视图进行MVC分页
- asp.net – Web部署删除IIS网站自定义配置
- asp.net-mvc – MVC使用asp.net Identity添加辅助
- asp.net-web-api – ASP.NET核心,Web API RouteA
- asp.net-mvc-3 – 工作单元和存储库模式是打算一
- asp.net – 你能使用基于属性的WebApi 2与WebFor
- OWIN上的CORS和访问/令牌导致“Access-Control-A
- asp.net下Repeater使用 AspNetPager分页控件
热点阅读
