Applying styles to a cell in Excel worksheet in .NET

Hi Team,

I have a scenario where Fill Effects and More Colors(for setting foreground color) have to be set for a single cell.

I tried doing that but when I apply one the other was not working.

Could you please help me in doing this with a sample code for cell B3 in the attached Example excel file.

Thanks in advance.

Regards,

Sanjeev

Hi,


Thanks for the template file and some details.

Please see the sample code below to mimic the B3 cell’s formatting in your provided template file sheet for your reference:
e.g
Sample code:
Workbook workbook = new Workbook();

Worksheet workSheet = workbook.getWorksheets().get(0);

workSheet.getCells().get(2, 1).putValue(100);

Style style = workSheet.getCells().get(“B3”).getStyle();

style.setForegroundColor(Color.fromArgb(203, 223, 241));

style.setPattern(BackgroundType.SOLID);

style.getFont().setColor(Color.getRed());

style.setHorizontalAlignment(TextAlignmentType.CENTER);

style.setVerticalAlignment(TextAlignmentType.CENTER);

workSheet.getCells().get(“B3”).setStyle(style);

workSheet.getCells().setRowHeightPixel(2, 53);

workSheet.getCells().merge(2, 1, 1, 2);

workbook.save(“out1.xlsx”);

Thank you.


Hi Amjad,

I tried with your suggestion but its not getting reflected. Actually what I'm doing is that with the following code I'm setting the gradient color which is in Fill Effects option of excel for the cell B3.

style.setGradient(true);

style.setTwoColorGradient(Color.fromArgb(255, 255, 255), Color.fromArgb(79, 129, 189), GradientStyleType.HORIZONTAL, 1);

After this I'm using the following code to set the foreground color of the same cell:

style.setForegroundColor(Color.fromArgb(203, 223, 241));

style.setPattern(BackgroundType.SOLID);

cells.get(2,1).setStyle(style);

Could you please help me on this.

Thanks in advance.

Regards,

Sanjeev

Hi,


Well, either you can set the Gradient color to the cell or set the background color of the cell. Actually first you specify the gradient color to the cell and then you are overwriting it by using setForegroundColor() method with specified solid pattern type as cell’s shading color.

Please see the sample code that works absolutely fine:
e.g
Sample code:
Workbook workbook = new Workbook();

Worksheet workSheet = workbook.getWorksheets().get(0);

workSheet.getCells().get(2, 1).putValue(100);

Style style = workSheet.getCells().get(“B3”).getStyle();

style.setGradient(true);

style.setTwoColorGradient(Color.fromArgb(255, 255, 255), Color.fromArgb(79, 129, 189), GradientStyleType.HORIZONTAL, 1);

style.getFont().setColor(Color.getRed());

style.setHorizontalAlignment(TextAlignmentType.CENTER);

style.setVerticalAlignment(TextAlignmentType.CENTER);

workSheet.getCells().get(“B3”).setStyle(style);

workSheet.getCells().setRowHeightPixel(2, 53);

workSheet.getCells().merge(2, 1, 1, 2);

workbook.save(“out1__mergedcellsformatting1.xlsx”);
Hope, it helps a bit.

Thank you.