的TableRow造型为导出到Excel [英] TableRow styling for Export To Excel

查看:135
本文介绍了的TableRow造型为导出到Excel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下,我使用导出到Excel的GridView的code。我加入了gridview的行成System.Web.UI.WebControls.Table。现在,我需要将背景颜色应用到导出的Excel表头和数据行(有两个标题行)。

I have following code that I am using for export to excel of a gridview. I am adding the gridview rows into System.Web.UI.WebControls.Table. Now, I need to apply background color to the header and data rows in the exported excel (There are two header rows).

我累了下面。它不提供所需的结果。

I tired the following. It is not providing the desired result.

目前解决的问题


  1. 一个标题行,没有背景颜色

  2. 着色施加于不具有数据单元(细胞的H,I,等等。)

我们如何纠正?

请注意:我想了解的导出功能。所以,请不建议使用任何第三方控件。我只是探索这一做法的所有功能。

Note: I am trying to learn the export feature. So, please don't suggest to use any third party controls. I am just exploring all features of this approach.

我加入分组头使用以下code原gridview的。

I am adding the header grouping to the original gridview using following code.

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();
    }
}

完成code

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评论,我尝试以下;仍然没有达到预期的结果。

Based on comment from Ankit, I tried the following; still the result is not as expected.

            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);
            }

推荐答案

我想出一个办法做到这一点......对于其他人的利益,我将它张贴在这里:

I figured a way to do it... For the benefit of others I will post it here:

参考文献:


  1. ASP.NET Excel导出编码的问题

  1. ASP.NET Excel export encoding problem

其他注意事项:当创建一个新的表TableSection可以用来定义标题

Other Note: When a new Table is created TableSection can be used to define header

 newRow.TableSection = TableRowSection.TableHeader;

code

//改变用于添加动态标题为HTML渲染的逻辑:

//Changed the logic used for adding dynamic header for HTML rendering:

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();


    }

}

//输出逻辑 - 应用类似的逻辑再次

//Export Logic - Applied similar logic once again

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);
        }
    }
}

这篇关于的TableRow造型为导出到Excel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆