Cell color changing in Excel using C#

C#ExcelMs Office

C# Problem Overview


I am using a Windows application for exporting a data table to Excel. It's working. Now I want to give some color for particular text in the cell. How shall I do this?

C# Solutions


Solution 1 - C#

For text:

[RangeObject].Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);

For cell background

[RangeObject].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);

Solution 2 - C#

Note: This assumes that you will declare constants for row and column indexes named COLUMN_HEADING_ROW, FIRST_COL, and LAST_COL, and that _xlSheet is the name of the ExcelSheet (using Microsoft.Interop.Excel)

First, define the range:

var columnHeadingsRange = _xlSheet.Range[    _xlSheet.Cells[COLUMN_HEADING_ROW, FIRST_COL],
    _xlSheet.Cells[COLUMN_HEADING_ROW, LAST_COL]];

Then, set the background color of that range:

columnHeadingsRange.Interior.Color = XlRgbColor.rgbSkyBlue;

Finally, set the font color:

columnHeadingsRange.Font.Color = XlRgbColor.rgbWhite;

And here's the code combined:

var columnHeadingsRange = _xlSheet.Range[
    _xlSheet.Cells[COLUMN_HEADING_ROW, FIRST_COL],
    _xlSheet.Cells[COLUMN_HEADING_ROW, LAST_COL]];

columnHeadingsRange.Interior.Color = XlRgbColor.rgbSkyBlue;

columnHeadingsRange.Font.Color = XlRgbColor.rgbWhite;

Solution 3 - C#

For C#, using the Workbook class (which implements the Workbook Interface) can provide lots of tools for coloring. I used Workbook (templateWorkbook in below example) as follows to set colors:

var copyFormating = templateWorkbook.Worksheets[sheetName].Cells[9,0].GetStyle();
copyFormating.ForegroundColor = System.Drawing.Color.Gold;
copyFormating.Font.Color = System.Drawing.Color.Black;
copyFormating.HorizontalAlignment = TextAlignmentType.Center;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSuryakavithaView Question on Stackoverflow
Solution 1 - C#Aseem GautamView Answer on Stackoverflow
Solution 2 - C#B. Clay Shannon-B. Crow RavenView Answer on Stackoverflow
Solution 3 - C#Andrew CurranView Answer on Stackoverflow