【发布时间】:2011-10-30 07:49:35
【问题描述】:
我将 GridView 绑定到 sqldatasource,然后在 _rowcreated 事件上进行一些验证,当行不符合要求时,我使用 e.Row.Visible = false 隐藏它;
这很好用,并且只在 gridview 中显示正确的行。现在我有一个按钮可以导出到 excel,除了导出隐藏的行之外,它的效果很好。我不想导出隐藏的行。
有没有一种方法可以告诉 gridview 不要添加该行而不是隐藏它? 在我运行导出之前,有没有一种简单的方法可以删除所有隐藏的行? 我可以在导出期间不添加隐藏行吗?正如您在下面的代码中看到的那样,我尝试执行此操作,但它无法识别该行是否可见。
导出代码:
public static 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();
gv.GridLines = GridLines.Both;
table.GridLines = gv.GridLines;
//table.BackColor = Color.Yellow;
// add the header row to the table
if (gv.HeaderRow != null)
{
GridViewExportUtil.PrepareControlForExport(gv.HeaderRow);
table.Rows.Add(gv.HeaderRow);
//color the header
table.Rows[0].BackColor = gv.HeaderStyle.BackColor;
table.Rows[0].ForeColor = gv.HeaderStyle.ForeColor;
}
// add each of the data rows to the table
foreach (GridViewRow row in gv.Rows)
{
if (row.Visible == true)
{
GridViewExportUtil.PrepareControlForExport(row);
table.Rows.Add(row);
}
}
// color the rows
bool altColor = false;
for (int i = 1; i < table.Rows.Count; i++)
{
if (!altColor)
{
table.Rows[i].BackColor = gv.RowStyle.BackColor;
altColor = true;
}
else
{
table.Rows[i].BackColor = gv.AlternatingRowStyle.BackColor;
altColor = false;
}
}
// 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();
}
}
}
【问题讨论】:
-
为什么一开始有隐藏行?只获取你想要显示的数据。
-
几乎所有的答案都在这里写一个(HtmlTextWriter)字符串或有互操作代码。两者都不要使用。这将导致您稍后在 DateTime 和 Decimal 格式方面出现问题。 Excel 也会发出警告,因为您生成的不是“真正的”Excel 文件,而是扩展名为 .xls 的 HTML 页面。开始使用专门的库来创建 Excel 文件,例如 EPPlus。 Example here 和 here.
标签: c# asp.net excel gridview export