Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cell color changing in Excel using C#

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?

like image 278
Suryakavitha Avatar asked Mar 16 '10 06:03

Suryakavitha


People also ask

Can I use IF function to change cell color?

To immediately spot negative values, you can highlight these cells using the if-function. As a starting point, prepare a list of all your accounting transactions. Mark the cells you want to highlight with colors according to their value. click on the tab named “Home” and find the button “Conditional formatting”.

How do you automatically change the color of a cell based on its value?

On the Home tab, in the Styles group, click Conditional Formatting > New Rule… (see step 2 of How to dynamically change a cell color based on value for step-by-step guidance). In the "New Formatting Rule" dialog, select the option "Use a formula to determine which cells to format".

How do I apply a formula to a colored cell in Excel?

On the home tab, in the Styles subgroup, click on Conditional Formatting→New Rule. Now select Use a formula to determine which cells to format option, and in the box type the formula: D3>5; then select Format button to select green as the fill color.


2 Answers

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); 
like image 73
Aseem Gautam Avatar answered Oct 01 '22 11:10

Aseem Gautam


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; 
like image 42
B. Clay Shannon-B. Crow Raven Avatar answered Oct 01 '22 12:10

B. Clay Shannon-B. Crow Raven