gpt4 book ai didi

Java POI 最后的 CellStyle 覆盖以前的 CellStyles

转载 作者:行者123 更新时间:2023-12-01 09:50:08 28 4
gpt4 key购买 nike

我正在使用 Java 中的 Apache POI 库构建 Excel 文件。我想要多个具有不同颜色的单元格,因此我创建了一种方法来构建我需要的样式。然后,我调用此方法来应用我需要的样式。

不幸的是,最后一个前景色被应用到之前应用了前景色样式的所有单元格。因此,当我在 C 列中创建灰色单元格时,我在 A 列中创建的黄色单元格会显示为灰色。[已编辑]

谁能告诉我我在这里做错了什么?

这是方法(抱歉其不雅)[已编辑]:

private CellStyle getCellStyle(boolean isHeader, boolean isShaded, String color){
CellStyle style = workbook.createCellStyle();
Font font = workbook.createFont();

if (isHeader) {
style.setBorderBottom(CellStyle.BORDER_MEDIUM);
style.setBorderLeft(CellStyle.BORDER_MEDIUM);
style.setBorderRight(CellStyle.BORDER_MEDIUM);
style.setBorderTop(CellStyle.BORDER_MEDIUM);

style.setAlignment(CellStyle.ALIGN_CENTER);

font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
font.setFontHeightInPoints((short) 14);
}

if (isShaded) {
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
if (color.equalsIgnoreCase("yellow"))
style.setFillForegroundColor(HSSFColor.YELLOW.index);
else if (color.equalsIgnoreCase("light grey"));
style.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
}

style.setFont(font);

return style;

}

这是我将该方法称为[已编辑]的部分。

private void createHeaderRow(Row row, String year, String tableName) {
int rowNum = row.getRowNum();
int colNum = 0;
boolean isHeader = true;

CellStyle boldStyle = getCellStyle(isHeader, false, "");
CellStyle yellowStyle = getCellStyle(isHeader, true, "yellow");
CellStyle lightGreyStyle = getCellStyle(isHeader, true, "light grey");

Cell cell = row.createCell(colNum++);
cell.setCellValue(year);
cell.setCellStyle(yellowStyle);

cell = row.createCell(colNum++);
cell.setCellValue("Company");
cell.setCellStyle(boldStyle);

cell = row.createCell(colNum++);
cell.setCellValue("Total");
cell.setCellStyle(lightGreyStyle);
}

最佳答案

问题不在于 Poi,请参见此处:

 else if (color.equalsIgnoreCase("light grey")); // <--- HERE
style.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);

您的else if没有执行任何操作,并且每次都会调用style.setFillForegroundColor(..GREY..)

即使没有必要,使用大括号来调节条件也是一种很好的做法。

菲菲:

if (isShaded) {
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
if (color.equalsIgnoreCase("yellow")){
style.setFillForegroundColor(HSSFColor.YELLOW.index);
}
else if (color.equalsIgnoreCase("light grey")){
style.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
}
}

刚刚测试了这段代码,似乎对我来说工作正常

关于Java POI 最后的 CellStyle 覆盖以前的 CellStyles,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37647984/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com