Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

java - 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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...