How to set background color for cell in Excel spreadsheet using C#.NET

Hi,

I am trying to set the backGroundColor for a cell as follows

cells["A10"].Style.BackgroundColor = Color.SkyBlue;

Can any one check this if i am doing anything wrong and help me out.

Thanks,

Srenvas

Hi Srenvas,

Thanks for considering Aspose.

Well, there are three types of color normally applied to a cell. i.e., ForegroundColor (refers to fill color or cell shading color), BackgroundColor (refers to background color, occasionally used) and Font Color (refers to font text color).

When you want to set a solid fill color (shading color) of a cell you may use ForgroundColor proper. The following code paints a yellow background color to the cell (You don't need to confuse with BackgroundColor property with it. You may use ForegroundColor property to set you desired back color of the cell. This code makes a yellow solid background) .

cell.Style.ForegroundColor = Color.Yellow;

cell.Style.Pattern = BackgroundType.Solid;

Well, BackgoundColor normally applied when you set pattern's BackgroundType (enum) to other than .None or other than .Solid. e.g.,

worksheet.Cells["A2"].Style.ForegroundColor=Color.Blue;

worksheet.Cells["A2"].Style.BackgroundColor=Color.Yellow;

worksheet.Cells["A2"].Style.Pattern=BackgroundType.VerticalStripe;

Here, the background fill color will be yellow with Blue Stripes in front of it.

For Font text color you may use:

cell.Style.Font.Color = Color.Red;

I write a simple example for you:

Workbook wb= new Workbook();

// If the color is not in the standard color palette you have to add it into the palette at an index position (0-55).

wb.ChangePalette(System.Drawing.Color.SkyBlue, 55);

Cells cells = wb.Worksheets[0].Cells;

Cell cell = cells[0,0];

cell.PutValue("Testing");

int index = wb.Styles.Add();

Style style = wb.Styles[index];

//For Cell's filling color

style.ForegroundColor = Color.SkyBlue;

style.Pattern = BackgroundType.Solid;

// For text color

style.Font.Color = Color.Red;

style.HorizontalAlignment = TextAlignmentType.Center;

cell.Style = style;

wb.Save("d:\\test\\testingclrs.xls");

Thank you.

Hi Sahi,

Thanks for that , so you mean to say that there are two layes for a cell while background color is applied or the foregroundcolor is applied

Thanks,

Srenva