Cell color changing in Excel using C#
C#ExcelMs OfficeC# 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;