我有以下代码用于导出到 gridview 的 excel。我将 gridview 行添加到 System.Web.UI.WebControls.Table 中。现在,我需要将背景颜色应用于导出的 excel 中的标题和数据行(有两个标题行)。
我累了以下。它没有提供预期的结果。
当前解决方案的问题
- 一个标题行没有背景颜色
- 着色应用于没有数据的单元格(单元格“H”、“I”等)
我们怎样才能纠正它?
注意:我正在尝试学习导出功能。所以,请不要建议使用任何第三方控件。我只是在探索这种方法的所有特性。
我正在使用以下代码将标题分组添加到原始网格视图。
protected void gvCustomers_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
System.Text.StringBuilder sbNewHeader = new StringBuilder();
sbNewHeader.AppendFormat(" </th>" +
"<th colspan='2' class='tableColGroupAssociate'>Associate Info <a href='#' class='associateHide'> Hide </a> </th>" +
"<th colspan='2' class='tableColGroupTransaction'>Financial Info <a href='#' class='financialHide'> Hide </a> </th>" +
"<th colspan='2' class='tableColGroupDailyTax'>Tax Info <a href='#' class='dailyTaxHide'> Hide </a> </th>"
+ "</tr>");
sbNewHeader.AppendFormat("<tr class='{0}'><th>{1}", this.gvCustomers.HeaderStyle.CssClass, e.Row.Cells[0].Text);
e.Row.Cells[0].Text = sbNewHeader.ToString();
}
}
完整代码
public static void Export(GridView gv)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "MyExcelFile.xls"));
HttpContext.Current.Response.ContentType = "application/ms-excel";
using (StringWriter stringWriter = new StringWriter())
{
using (HtmlTextWriter tetxWriter = new HtmlTextWriter(stringWriter))
{
System.Web.UI.WebControls.Table tableControl = new Table();
tableControl.GridLines = gv.GridLines;
//Before the next step - we can remove any controls inside the gridview and replace with literal control
// Add the header row to the table
if (gv.HeaderRow != null)
{
TableRow tableRow = gv.HeaderRow;
tableRow.Style[System.Web.UI.HtmlTextWriterStyle.BackgroundColor] = "Orange";
tableControl.Rows.Add(gv.HeaderRow);
}
// Add each of the data rows to the table
foreach (GridViewRow row in gv.Rows)
{
TableRow tableRow = row;
tableRow.Style[System.Web.UI.HtmlTextWriterStyle.BackgroundColor] = "Yellow";
tableControl.Rows.Add(row);
}
// Render the table into the htmlwriter
tableControl.RenderControl(tetxWriter);
// Render the htmlwriter into the response
HttpContext.Current.Response.Write(stringWriter.ToString());
HttpContext.Current.Response.End();
}
}
}
编辑
根据 Ankit 的评论,我尝试了以下方法;结果仍然不如预期。
if (gv.HeaderRow != null)
{
TableRow tableRow = gv.HeaderRow;
foreach (TableCell cell in tableRow.Cells)
{
cell.Style[System.Web.UI.HtmlTextWriterStyle.BackgroundColor] = "Orange";
}
tableControl.Rows.Add(gv.HeaderRow);
}