Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Styles to Excel Cell POI

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);
like image 1000
rupesh_padhye Avatar asked Sep 24 '15 11:09

rupesh_padhye


People also ask

Which method is used to get the format of the particular cell in Apache POI?

Class DataFormatter. DataFormatter contains methods for formatting the value stored in a Cell.


1 Answers

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 CellStyles 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 CellStyles. 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 CellStyles, but if a different combination of attributes is required, then you must create and use a new CellStyle.

like image 56
rgettman Avatar answered Oct 23 '22 03:10

rgettman