Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Highlighting the data with different colors in Excel Using C# in Windows Applications

I am working with a Windows application. I need to work out how to highlight the data with different colors & styles in Excel. I am using C# to export the data to excel.

This is the code I am using to export a DataTable into Excel,

private void btnExportexcel_Click(object sender, EventArgs e)
{
    oxl = new Excel.Application();
    oxl.Visible = true;
    oxl.DisplayAlerts = false;

    wbook = oxl.Workbooks.Add(Missing.Value);

    wsheet = (Excel.Worksheet)wbook.ActiveSheet;
    wsheet.Name = "Customers";

    DataTable dt = clsobj.convert_datagrid_orderlist_to_datatable(dvgorderlist);

    int rowCount = 1;
    foreach (DataRow dr in dt.Rows)
    {
        rowCount += 1;
        for (int i = 1; i < dt.Columns.Count + 1; i++)
        {
            // Add the header the first time through
            if (rowCount == 2)
            {
                wsheet.Cells[1, i] = dt.Columns[i - 1].ColumnName;
            }
                wsheet.Cells[rowCount, i] = dr[i - 1].ToString();
            }
        }

        range = wsheet.get_Range(wsheet.Cells[1, 1],
        wsheet.Cells[rowCount, dt.Columns.Count]);
        range.EntireColumn.AutoFit();
    }

    wsheet = null;
    range = null;
}
like image 631
user285008 Avatar asked Dec 28 '22 23:12

user285008


1 Answers

You need to get the 'Interior' object of the cell or range and set the colour on it.

Range cellRange = (Range)wsheet.Cells[rowCount, i];
cellRange.Interior.Color = 255;

Excel colours are an integer sequence, so you have to calculate the value for the colour your want. You might find this method helpful:

public static int ConvertColour(Color colour)
{
    int r = colour.R;
    int g = colour.G * 256;
    int b = colour.B * 65536;

    return r + g + b;
}

Then you can just do this:

cellRange.Interior.Color = ConvertColour(Color.Green);

You can set the style of the text using the .font property:

cellRange.Font.Size = "20";
cellRange.Font.Bold = true;

There are other properties like Color, Italic and Underline which you can use to get the style you need.

like image 119
Simon P Stevens Avatar answered Jan 05 '23 16:01

Simon P Stevens