Free Support Forum - aspose.com

Format table headers

I am using the following cxode to set the background color and foreground color.


sheet.getCells().get(“A1”).getStyle().setBackgroundColor(com.aspose.cells.Color.getGray());
sheet.getCells().get(“A1”).getStyle().setForegroundColor(com.aspose.cells.Color.getWhite());

It has not effect on the outputed spreadsheet. Is this the incorrect way of doing this? What is the right way?

Thank you,
David

Hi,

Thanks for your posting and using Aspose.Cells.

In order to set the background color, you need to set the foreground color property. Please see the following sample code for your more help.

Java


Workbook workbook = new Workbook();


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


Cell cell = sheet.getCells().get(“A1”);


Style style = cell.getStyle();


style.setPattern(BackgroundType.SOLID );

style.setForegroundColor(Color.getYellow());


cell.setStyle(style);


workbook.save(“output.xlsx”);


1 Like

I am setting the foreground. That is a lot of lines of code for setting the style to one cell. I added logic to set the pattern as shown but still no luck. Of note I save my workbook to the output stream. Not as a file on the server.

Is there a way to apply a style to an entire row? Not the whole table and not an individual cell.

Hi,

See the sample code on how to apply formatting to a whole row for your reference:

Sample code:

Workbook workbook = new Workbook();
Worksheet sheet = workbook.getWorksheets().get(0);

Cells cells = sheet.getCells();
Style style = workbook.getStyles().get(workbook.getStyles().add());
style.setForegroundColor(Color.getYellow());
style.setPattern(BackgroundType.SOLID);
StyleFlag flag = new StyleFlag();
flag.setCellShading(true);

//Accessing the first row from the Rows collection
Row row = cells.getRow(0);

//Assigning the Style object to the Style property of the row
row.applyStyle(style, styleFlag);
workbook.save("range_style_book.xlsx");

See the document for your reference:
http://www.aspose.com/docs/display/cellsjava/Formatting+Rows++and++Columns

Let us know if you have any other issue or confusion.

Thank you.

cells.getRow() is deprecated. is there another appropriate function?

Hi,


Yes, sorry for this, the cells.getRow() method is deprecated in newer version, please use cells.getRows().get() instead. See the updated sample code for your complete reference:
Sample code:

Workbook workbook = new Workbook();
Worksheet sheet = workbook.getWorksheets().get(0);

Cells cells = sheet.getCells();

Style style = workbook.getStyles().get(workbook.getStyles().add());
style.setForegroundColor(Color.getYellow());
style.setPattern(BackgroundType.SOLID);
StyleFlag flag = new StyleFlag();
flag.setCellShading(true);

//Accessing the first row from the Rows collection
Row row = cells.getRows().get(0);

//Assigning the Style object to the Style property of the row
row.applyStyle(style, flag);

workbook.save(“range_style_book.xlsx”);