将Datagridview导出到Excel文件使用更改的颜色单元格

时间:2013-12-07 03:48:55

标签: c# export-to-excel

我的datagridview列比较了一些数据,并匹配红色的不同颜色或绿色的相同数据。我有个问题。我想将我的datagridview导出到excel文件,但创建的excel文件只包含文本。我想要显示excel报告与datagridview相同 - 绿色或红色的匹配数据。这是我的代码

// comparing data in datagridview
    public void Compare() 
    {
        try
        {
            int rowCount = DataGridView.RowCount;
            int colCount = DataGridView.ColumnCount;
            string col1,
                   col2;

            int c = 1;
            for (int k = 0; k < rowCount - 1; k++)
            {
                for (int i = 0; i < colCount; i++, c++)
                {
                    col1= Convert.ToString(DataGridView.Rows[k].Cells[0].Value);
                    col2= Convert.ToString(DataGridView.Rows[k].Cells[1].Value);

                    for (int j = 0; j < rowCount - 1; j++)
                    {
                        string col3= Convert.ToString(DataGridView.Rows[k].Cells[2].Value);
                        string col4= Convert.ToString(DataGridView.Rows[k].Cells[3].Value);

                        // comparing data in col1 and col3
                        if (col1 == col3 && (col1 != "" && col3 != ""))
                        {
                            DataGridViewCellStyle CellStyle = new DataGridViewCellStyle();
                            CellStyle.BackColor = Color.LightGreen;
                            DataGridView.Rows[k].Cells[0].Style = CellStyle;
                            DataGridView.Rows[k].Cells[2].Style = CellStyle;
                        }
                        else
                        {
                            DataGridViewCellStyle CellStyle = new DataGridViewCellStyle();
                            CellStyle.BackColor = Color.Red;
                            DataGridView.Rows[k].Cells[0].Style = CellStyle;
                            DataGridView.Rows[k].Cells[2].Style = CellStyle;
                        }

                        // comparing data in col2 and col4
                        if (col2 == col4 && (col2 != "" && col4 != ""))
                        {
                            DataGridViewCellStyle CellStyle = new DataGridViewCellStyle();
                            CellStyle.BackColor = Color.LightGreen;
                            DataGridView.Rows[k].Cells[1].Style = CellStyle;
                            DataGridView.Rows[k].Cells[3].Style = CellStyle;
                        }
                        else
                        {
                            DataGridViewCellStyle CellStyle = new DataGridViewCellStyle();
                            CellStyle.BackColor = Color.Red;
                            DataGridView.Rows[k].Cells[1].Style = CellStyle;
                            DataGridView.Rows[k].Cells[3].Style = CellStyle;
                        }
                    }
                }
            }
            DataGridView.ClearSelection();
        }
        catch (Exception) 
        {

        }
    }

如何将此修改后的datagridview导出为ex​​cel。在此先感谢您的帮助

1 个答案:

答案 0 :(得分:0)

请尝试以下代码段

gv.HeaderRow.BackColor = System.Drawing.Color.Lavender;
gv.HeaderRow.ForeColor = System.Drawing.Color.Green;

例如

public static void ExportGridView(string fileName, GridView gv, Label header, Label date)
        {
            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))
                {
                    gv.AllowPaging = false;
                    //  Create a table to contain the grid
                    Table table = new Table();

                    //  include the gridline settings
                    table.GridLines = gv.GridLines;

                    gv.Style["font-family"] = "Tahoma";
                    //  add the header row to the table

                    if (gv.HeaderRow != null)
                    {
                        GridViewExportUtil.PrepareControlForExport(gv.HeaderRow);
                        gv.HeaderRow.BackColor = System.Drawing.Color.Lavender;
                        gv.HeaderRow.ForeColor = System.Drawing.Color.Green;

                        table.Rows.Add(gv.HeaderRow);
                    }
                    //  add each of the data rows to the table
                    foreach (GridViewRow row in gv.Rows)
                    {
                        GridViewExportUtil.PrepareControlForExport(row);
                        table.Rows.Add(row);
                    }
                    //  add the footer row to the table
                    if (gv.FooterRow != null)
                    {
                        GridViewExportUtil.PrepareControlForExport(gv.FooterRow);
                        table.Rows.Add(gv.FooterRow);
                    }
                    htw.WriteLine("<br>");
                    // htw.WriteLine("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
                    if (header.Text != null)
                    {
                        header.Font.Size = 15;
                        header.Font.Bold = true;
                        header.ForeColor = System.Drawing.Color.Blue;
                        header.RenderControl(htw);
                    }
                    htw.WriteLine("</p>");
                    //  render the table into the htmlwriter
                    table.RenderControl(htw);
                    htw.WriteLine("<br>");
                    htw.WriteLine("Report taken on :", System.Drawing.FontStyle.Bold);
                    if (date.Text != null)
                    {
                        date.ForeColor = System.Drawing.Color.Blue;
                        date.RenderControl(htw);
                    }
                    //  render the htmlwriter into the response
                    HttpContext.Current.Response.Write(sw.ToString());
                    HttpContext.Current.Response.End();
                }
            }
        }

支持方法是

    /// <summary>
    /// Replace any of the contained controls with literals
    /// </summary>
    /// <param name="control"></param>
    private static void PrepareControlForExport(Control control)
        {
            for (int i = 0; i < control.Controls.Count; i++)
            {
                Control current = control.Controls[i];
                if (current is LinkButton)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));
                }
                else if (current is ImageButton)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));
                }
                else if (current is HyperLink)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));
                }
                else if (current is DropDownList)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));
                }
                else if (current is CheckBox)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
                }
                else if (current is Label)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, new LiteralControl((current as Label).Text));
                }

                if (current.HasControls())
                {
                    GridViewExportUtil.PrepareControlForExport(current);
                }
            }
        }