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?
Asked
Active
Viewed 1.9e+01k times
3 Answers
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
-
29You can avoid the clutter of `System.Drawing.ColorTranslator` by using `Excel.XlRgbColor.rgbRed` instead. – kmote Oct 07 '15 at 15:46
-
How can I sort by cell color? – Si8 Dec 19 '16 at 16:08
-
1Using this on Cells property erases borders. Using this on Range property with two indexers causes a COM exception. – Apr 04 '18 at 14:25
-
Why is it ColorTranslator.ToOle but not ColorTranslator.ToWin32? – Jyunhao Shih Sep 10 '19 at 02:19
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;

Andrew Curran
- 11
- 2