我尝试创建一个 xlsx 文件。
我有这个代码:
public static void main(String[] args){
Workbook workbook = new XSSFWorkbook();
//create sheet
Sheet sheet = workbook.createSheet("Test");
//cell style for data
CellStyle dataCellStyle = workbook.createCellStyle();
dataCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
for(int i = 0; i < 10; i++){
//create row
Row row = sheet.createRow(i);
//THIS IF
//set intermittent background color
if(dataCellStyle.getFillForegroundColor() != IndexedColors.WHITE.getIndex()){
//NEVER ENTER HERE
dataCellStyle.setFillForegroundColor(IndexedColors.WHITE.getIndex());
}else{
//ENTER ONLY HERE
dataCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
}
Cell cell = row.createCell(0);
cell.setCellValue(i);
cell.setCellStyle(dataCellStyle);
}
try {
FileOutputStream out = new FileOutputStream("workbook.xlsx");
workbook.write(out);
out.close();
}catch(Exception e){ e.printStackTrace(); }
}
结果如下所示:
我尝试让单元格的颜色变得断断续续。一种白色,一种灰色。
值为 0、2、4、6、8
的单元格背景应为白色,其他背景为灰色。
if
出了什么问题?
最佳答案
线路
if(dataCellStyle.getFillForegroundColor() != IndexedColors.WHITE.getIndex()){
必须是这样的:
if(i % 2 == 0){
关于java - Apache POI - 单元格的间歇颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57185994/