【问题标题】:TableRow styling for Export To Excel导出到 Excel 的 TableRow 样式
【发布时间】:2012-09-21 07:18:15
【问题描述】:

我有以下代码用于导出到网格视图的 excel。我将 gridview 行添加到 System.Web.UI.WebControls.Table 中。现在,我需要将背景颜色应用于导出的 excel 中的标题和数据行(有两个标题行)。

我厌倦了以下。它没有提供预期的结果。

当前解决方案的问题

  1. 一个标题行没有背景颜色
  2. 着色应用于没有数据的单元格(单元格“H”、“I”等)

我们如何纠正它?

注意:我正在尝试学习导出功能。所以,请不要建议使用任何第三方控件。我只是在探索这种方法的所有功能。

我正在使用以下代码将标题分组添加到原始网格视图。

protected void gvCustomers_RowCreated(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.Header)
    {
        System.Text.StringBuilder sbNewHeader = new StringBuilder();
        sbNewHeader.AppendFormat("&nbsp;</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);
            }


【问题讨论】:

  • 我得到的是您正在复制整个 gridView 行并将其粘贴到 Excel 行中。对于您的问题,我有一个解决方法,但不建议这样做,因为您将使用不必要的嵌套循环只是为了格式化,如果您觉得没问题,那么您可以在循环中为行再使用一个循环,那么您将每次为每个单元格而不是一行添加值,则gridView区域之外的单元格将不会获得颜色。
  • @Ankit 谢谢。我试过你的建议。如更新的问题所示,仍然存在问题。有什么建议吗?
  • 能否请您逐步调试该过程以了解那里实际发生的情况。

标签: c# asp.net .net


【解决方案1】:

如果您想更好地控制 excel 文件的编写方式,请查看 ClosedXML

添加表格就这么简单

var wb = new XLWorkbook();
wb.Worksheets.Add(myDataTable);
wb.SaveAs("MySheet.xlsx");

使用 API,您可以编写如下代码:

var rngTable = ws.Range("B2:F6");
rngTable.FirstCell().Style
    .Font.SetBold()
    .Fill.SetBackgroundColor(XLColor.CornflowerBlue)
    .Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center);

【讨论】:

  • 写出 html 并让 excel 弄清楚如何显示它永远不会让您完全控制输出。与RenderControl 方法相比,我总是更喜欢这种方法。
【解决方案2】:

我想出了一个办法……为了其他人的利益,我会在这里发布:

参考资料:

  1. ASP.NET Excel export encoding problem

其他注意:新建表时可以使用TableSection来定义表头

 newRow.TableSection = TableRowSection.TableHeader;

代码

//更改了为HTML渲染添加动态标题的逻辑:

protected void gvCustomers_RowCreated(object sender, GridViewRowEventArgs e)
{

    if (e.Row.RowType == DataControlRowType.Header)
    {
        GridViewRow newHeaderRow = new GridViewRow(-1, -1, DataControlRowType.Header, DataControlRowState.Normal);

        TableCell cell1 = new TableHeaderCell();
        cell1.ColumnSpan = 1; //e.Row.Cells.Count;
        cell1.Text = "";

        TableCell cell2 = new TableCell();
        cell2.ColumnSpan = 2;
        cell2.Text = "One";

        TableCell cell3 = new TableCell();
        cell3.ColumnSpan = 2;
        cell3.Text = "Two";

        TableCell cell4 = new TableCell();
        cell4.ColumnSpan = 2;
        cell4.Text = "Three";

        newHeaderRow.Cells.Add(cell1);
        newHeaderRow.Cells.Add(cell2);
        newHeaderRow.Cells.Add(cell3);
        newHeaderRow.Cells.Add(cell4);

        ((GridView)sender).Controls[0].Controls.AddAt(0, newHeaderRow);
    }

    if (e.Row.RowType == DataControlRowType.Header)
    {

        //System.Text.StringBuilder sbNewHeader = new StringBuilder();
        //sbNewHeader.AppendFormat("&nbsp;</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";


    //Response.ContentEncoding = System.Text.Encoding.Unicode;
    //Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());


    using (StringWriter stringWriter = new StringWriter())
    {
        using (HtmlTextWriter tetxWriter = new HtmlTextWriter(stringWriter))
        {

            System.Web.UI.WebControls.Table tableControl = new Table();
            tableControl.GridLines = gv.GridLines;

            //  Add the header row to the table
            if (gv.HeaderRow != null)
            {
                ReplaceControlForExport(gv.HeaderRow);


                #region Dynamic Frrst Header Row

                TableRow newRow = new TableRow();

                TableCell cell1 = new TableHeaderCell();
                cell1.ColumnSpan = 1; 
                cell1.Text = "";

                TableCell cell2 = new TableCell();
                cell2.ColumnSpan = 2;
                cell2.Text = "One";

                TableCell cell3 = new TableCell();
                cell3.ColumnSpan = 2;
                cell3.Text = "Two";

                TableCell cell4 = new TableCell();
                cell4.ColumnSpan = 2;
                cell4.Text = "Three";

                newRow.Cells.Add(cell1);
                newRow.Cells.Add(cell2);
                newRow.Cells.Add(cell3);
                newRow.Cells.Add(cell4);

                foreach (TableCell cell in newRow.Cells)
                {
                    cell.Style[System.Web.UI.HtmlTextWriterStyle.BackgroundColor] = "Purple";
                }
                tableControl.Rows.Add(newRow);

                #endregion 

                TableRow originalHeaderRow = gv.HeaderRow;
                foreach (TableCell cell in originalHeaderRow.Cells)
                {
                    cell.Style[System.Web.UI.HtmlTextWriterStyle.BackgroundColor] = "Orange";
                }
                tableControl.Rows.Add(originalHeaderRow);
            }


            //  Add each of the data rows to the table
            foreach (GridViewRow row in gv.Rows)
            {
                ReplaceControlForExport(row);

                TableRow tableRow = row;
                foreach (TableCell cell in tableRow.Cells)
                {
                    cell.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();


        }
    }
  }

 private static void ReplaceControlForExport(Control mainControlElement)
 {
    for (int i = 0; i < mainControlElement.Controls.Count; i++)
    {
        Control currentControl = mainControlElement.Controls[i];

        if (currentControl is LinkButton)
        {
            mainControlElement.Controls.Remove(currentControl);
            mainControlElement.Controls.AddAt(i, new LiteralControl((currentControl as LinkButton).Text));
        }
        else if (currentControl is ImageButton)
        {
            mainControlElement.Controls.Remove(currentControl);
            mainControlElement.Controls.AddAt(i, new LiteralControl((currentControl as ImageButton).AlternateText));
        }
        else if (currentControl is HyperLink)
        {
            mainControlElement.Controls.Remove(currentControl);
            mainControlElement.Controls.AddAt(i, new LiteralControl((currentControl as HyperLink).Text));
        }
        else if (currentControl is DropDownList)
        {
            mainControlElement.Controls.Remove(currentControl);
            mainControlElement.Controls.AddAt(i, new LiteralControl((currentControl as DropDownList).SelectedItem.Text));
        }
        else if (currentControl is CheckBox)
        {
            mainControlElement.Controls.Remove(currentControl);
            mainControlElement.Controls.AddAt(i, new LiteralControl((currentControl as CheckBox).Checked ? "True" : "False"));
        }

        //Recursive Call
        if (currentControl.HasControls())
        {
            ReplaceControlForExport(currentControl);
        }
    }
}

【讨论】:

    猜你喜欢
    • 2019-04-01
    • 2020-09-04
    • 2018-05-14
    • 2019-11-24
    • 1970-01-01
    • 1970-01-01
    • 2010-10-25
    • 1970-01-01
    • 2018-07-26
    相关资源
    最近更新 更多