问题的根本在于Excel中不同的单元格样式由不同的CellStyle对象表示,而getCellStyle只返回CellStyle的副本,因此setCellStyle的调用将导致新的CellStyle对象的创建,从而修改背景颜色。
解决方案是将原始单元格样式的所有属性复制到一个新的CellStyle对象中,并将其用作setCellStyle的参数。以下是示例代码:
// 获取单元格 Cell cell = row.getCell(0);
// 获取单元格样式 CellStyle originalStyle = cell.getCellStyle();
// 创建新样式对象,将颜色属性复制到其中 CellStyle newStyle = workbook.createCellStyle(); newStyle.cloneStyleFrom(originalStyle); newStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
// 将新样式应用于单元格 cell.setCellStyle(newStyle);