Excel 个单元格 POI 的多种样式

Multiple Styles to Excel Cell POI

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

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

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

解决方案是创建另一个 CellStyle,它具有其他两个 CellStyle 的所需属性。可以用the cloneStyleFrom method开始一个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);

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

您可以创建样式映射,然后您可以在整个 java 程序中使用不同的样式。

例如

Map<String, CellStyle> cellStyles = new HashMap<String, CellStyle>();
DataFormat dataFormat = workbook.createDataFormat();

XSSFCellStyle cellStyle;
XSSFFont font;

cellStyle = workbook.createCellStyle();

cellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
cellStyle.setAlignment(cellStyle.ALIGN_CENTER_SELECTION);   
font = workbook.createFont();
font.setFontHeightInPoints((short)16);
font.setFontName("Calibri");                                            
cellStyle.setFont(font);
cellStyles.put("header_cell_style", cellStyle);

cellStyle = workbook.createCellStyle(); 
cellStyle.setAlignment(cellStyle.ALIGN_CENTER_SELECTION);
font = workbook.createFont();
font.setFontHeightInPoints((short)12);
font.setFontName("Calibri");                   
cellStyle.setFont(font);
cellStyles.put("normal_cell_style", cellStyle);

cellStyle = workbook.createCellStyle();
cellStyle.setAlignment(cellStyle.ALIGN_CENTER_SELECTION);       
cellStyle.setDataFormat(dataFormat.getFormat("dd-mmm-yyyy"));
font = workbook.createFont();
font.setFontHeightInPoints((short)12);
font.setFontName("Calibri");                   
cellStyle.setFont(font);
cellStyles.put("date_cell_style", cellStyle);

cellStyle = workbook.createCellStyle();
cellStyle.setAlignment(cellStyle.ALIGN_CENTER_SELECTION);       
cellStyle.setDataFormat(dataFormat.getFormat("dd-mmm-yyyy"));
font = workbook.createFont();
font.setFontHeightInPoints((short)16);
font.setFontName("Calibri");                   
cellStyle.setFont(font);
cellStyles.put("header_date_cell_style", cellStyle);

return cellStyles;       

然后像这样使用这张地图

Map<String, CellStyle> multipleCellStyles = createMultipleExcelCellStyles(workbook);

headerCellD1.setCellStyle(multipleCellStyles.get("header_cell_style"));

cellB.setCellStyle(multipleCellStyles.get("normal_cell_style"));

cellC.setCellStyle(multipleCellStyles.get("date_cell_style"));