Search code examples
c#excelwinformsdatagridviewexport-to-excel

Export DataGridVeiw to excel in C# with cell background colors


I have made a Shift Roster in DataGridView in winform C#. This is the excel sheet screenshot which I have exported from DataGridView.

I need to export DataGridView as it is to Excel Sheet maintaining the font color and background color also I want not to export first column of DataGridView to excel which is invisible.

I have used the following code to export DataGridView to Excel.

using (ExcelPackage pck = new ExcelPackage(file))
{
    // Add a new worksheet to the empty workbook
    ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Sheet1");
    // Load data from DataTable to the worksheet
    ws.Cells["A1"].LoadFromDataTable(((DataTable)gvShift.DataSource), true);
    ws.Cells.AutoFitColumns();

    // Add some styling
    using (ExcelRange rng = ws.Cells[1, 1, 1, gvShift.Columns.Count])
    {
        rng.Style.Font.Bold = true;
        rng.Style.Fill.PatternType = ExcelFillStyle.Solid;
        rng.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.FromArgb(79, 129, 189));
        rng.Style.Font.Color.SetColor(System.Drawing.Color.White);
    }

Kindly Help Please....


Solution

  • you can use cells.interior.color

    Range range = 
                oSheet.get_Range("A" + redRows.ToString(), "J"
                                        + redRows.ToString());
    
        range.Cells.Interior.Color = System.Drawing.Color.Red;