77

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?

Konrad Viltersten
  • 36,151
  • 76
  • 250
  • 438
Suryakavitha
  • 1,371
  • 5
  • 33
  • 49

3 Answers3

158

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);
A G
  • 21,087
  • 11
  • 87
  • 112
17

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;
Massimiliano Kraus
  • 3,638
  • 5
  • 27
  • 47
B. Clay Shannon-B. Crow Raven
  • 8,547
  • 144
  • 472
  • 862
1

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;