I want to apply colour to cell as well as Format Cell value(e.g. Date,Amount).But when I am applying two Cell Style only the last style is gets applied on cell.
//before this colourCellStyle and dateCellStyle are the formatting style
cell9 = row.createCell(9);
cell9.setCellValue(getLoadDate());
cell9.setCellStyle(colourCellStyle);
cell9.setCellStyle(dateCellStyle);
Class DataFormatter. DataFormatter contains methods for formatting the value stored in a Cell.
Multiple cell styles cannot be applied to a single Cell
. The last cell style applied will overwrite any pre-existing cell style on the Cell
. Setting multiple CellStyle
s won't combined the set attributes of each style.
The solution is to create another CellStyle
that has the desired attributes of both of the other CellStyle
s. You can use the cloneStyleFrom
method to start with the attributes of one CellStyle
.
CellStyle combined = workbook.createCellStyle();
combined.cloneStyleFrom(colourCellStyle);
combined.setDataFormat(dateCellStyle.getDataFormat());
// You can copy other attributes to "combined" here if desired.
cell9.setCellStyle(combined);
This technique can be generalized to clone any existing cell style and copy individual attributes from a second existing cell style. As always, reuse any existing CellStyle
s, but if a different combination of attributes is required, then you must create and use a new CellStyle
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With