gpt4 book ai didi

java - 如何设置空白单元格的颜色

转载 作者:行者123 更新时间:2023-11-30 05:54:58 25 4
gpt4 key购买 nike

我需要为一整行设置颜色,但问题是我的一些单元格是空白单元格,不包含任何数据,

        XSSFRow row2 = sheet.getRow(1);

CellStyle style = wb.createCellStyle();
style.setFillForegroundColor(IndexedColors.GREEN.getIndex());
style.setFillPattern(CellStyle.SOLID_FOREGROUND);

for (int i = 0; i < row1.getLastCellNum() + 1; i++) {// For each cell in the row
row2.getCell(i).setCellStyle(style);// Set the style
}

我遇到这样的错误:

java.lang.NullPointerException

我相信此错误来自空白单元格,因为当我尝试在包含数据的单元格上设置颜色时:

row2.getCell(4).setCellStyle(style);

特定单元格具有相应的颜色。

我们真的可以在空白单元格上添加颜色吗?

最佳答案

您应该尝试以下方法。在这里我给了你逻辑,因为我没有完全的依赖关系,请按照下面的方法首先检查 row2.getCell 是否不为空,然后设置,否则创建单元格,然后设置。

 XSSFRow row2 = sheet.getRow(1);

CellStyle style = wb.createCellStyle();
style.setFillForegroundColor(IndexedColors.GREEN.getIndex());
style.setFillPattern(CellStyle.SOLID_FOREGROUND);

for (int i = 0; i < row2.getLastCellNum(); i++) {// For each cell in the row
if( row2.getCell(i)!=null){
row2.getCell(i).setCellStyle(style);// Set the style
}else{
Cell cell=row2.createCell(i);
cell.setCellStyle(style);
}
}

关于java - 如何设置空白单元格的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53333361/

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