2013-12-07 3 views
0

Мои столбцы datagridview сравнивают некоторые данные и соответствуют разным цветам по красному или одинаковым данным по зеленому цвету. У меня проблема. Я хочу экспортировать datagridview в файл excel, но созданный файл excel содержит только текст. Я хочу показать, что excel сообщает то же, что и в datagridview, - с соответствующими данными по зеленому или красному. Вот мой кодЭкспорт Datagridview в файл Excel С измененными ячейками цвета

// 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 в excel. Заранее спасибо за помощь

ответ

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); 
       } 
      } 
     } 
Смежные вопросы