【发布时间】:2013-10-11 06:46:53
【问题描述】:
我在 POI 条件格式方面遇到了一些问题。我不完全了解 POI 在这里所做的事情。 我正在为值超过 70 的单元格值设置背景颜色格式规则。我想在我的应用程序中获取该 CellStyle(通过条件格式规则应用),但 POI 不会返回更新的单元格样式,而是返回默认值.这是我的代码
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet();
sheetConditionalFormatting sheetCF = sheet
.getSheetConditionalFormatting();
// Condition 1: Cell Value Is greater than 70 (Blue Fill)
ConditionalFormattingRule rule1 = sheetCF
.createConditionalFormattingRule(ComparisonOperator.GT, "70");
PatternFormatting fill1 = rule1.createPatternFormatting();
fill1.setFillBackgroundColor(IndexedColors.BLUE.index);
fill1.setFillPattern(PatternFormatting.SOLID_FOREGROUND);
CellRangeAddress[] regions = { CellRangeAddress.valueOf("A1:C10") };
int index = sheetCF.addConditionalFormatting(regions, rule1);
sheet.createRow(0).createCell(0).setCellValue(84);
sheet.createRow(1).createCell(0).setCellValue(60);
sheet.createRow(2).createCell(0).setCellValue(50);
sheet.createRow(3).createCell(0).setCellValue(51);
sheet.createRow(4).createCell(0).setCellValue(49);
sheet.createRow(5).createCell(0).setCellValue(41);
Cell cell = sheet.getRow(0).getCell(0);
CellStyle style = cell.getCellStyle();
System.out.println("style index : "+style.getIndex()+" value:"+cell.getNumericCellValue());
使用上面的代码,style.getIndex() 总是返回 0(即默认格式)。我觉得它应该返回带有背景颜色的更新格式样式。当我在实际的 xlsx 文件中编写上述工作簿并使用 MSExcel 打开时,我可以看到第一个单元格的背景颜色。同样,当我从 xlsx 文件将其读取到 POI 工作簿时,它不会返回具有背景颜色的单元格样式。
有没有人尝试过/遇到过同样的问题?
问候, 阿扎尔
【问题讨论】:
-
可能“样式索引”是指一种静态样式,并且无论如何都不会因条件而改变? "Style" 是定义的,我不希望它随着值的变化而改变。 格式更改。您是否可以在 POI 中选择它取决于他们对 MS 实施的怪癖的追逐程度。我不会依赖它。
-
实际上,当我使用' cellStyle.setFillBackgroundColor() 和 cellStyle.setFillForegroundColor' 更改单元格样式时,POI 会创建新的 cellStyle 并且相应的单元格会返回新创建的样式,但是当单元格时不会发生这种情况是通过条件格式格式化的。
-
您知道 Excel 中的单元格样式和条件格式是两个完全不同的东西吗?
-
尝试用 setFillForegroundColor 颜色代替 setFillBackgroundColor.stackoverflow.com/questions/17243529/…
-
@Gagravarr:我认为无论您如何更改单元格格式(通过条件格式/直接单元格样式属性),单元格样式都应该更改。如果不是,那么很难获得通过条件格式应用的样式。我不确定 POI/Excel 如何做到这一点?如果它不同,那么我怎么能通过条件格式规则格式化单元格样式。我坚持这个。任何指针将不胜感激。
标签: java apache-poi