多个样式到Excel单元格POI

rup*_*hye 5 java apache-poi

我想将颜色应用于单元格以及格式化单元格值(例如日期,金额).但是当我应用两个单元格样式时,只有最后一个样式应用于单元格.

//before this colourCellStyle and dateCellStyle are the formatting style
cell9 = row.createCell(9);
cell9.setCellValue(getLoadDate());
cell9.setCellStyle(colourCellStyle);
cell9.setCellStyle(dateCellStyle);
Run Code Online (Sandbox Code Playgroud)

rge*_*man 7

多个单元格样式不能应用于单个单元格Cell.应用的最后一个单元格样式将覆盖任何预先存在的单元格样式Cell.设置多个CellStyles不会合并每个样式的设置属性.

解决方案是创建另一个CellStyle具有其他CellStyles 的所需属性的解决方案.您可以使用cloneStyleFrom方法从一个属性开始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);
Run Code Online (Sandbox Code Playgroud)

可以推广该技术以克隆任何现有的单元格样式并从第二现有单元格样式复制单个属性.与往常一样,重用任何现有的CellStyles,但如果需要不同的属性组合,则必须创建并使用新的CellStyle.