java - Apache POI - 单元格的间歇颜色

标签 java apache-poi

我尝试创建一个 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/

相关文章:

java - Apache POI - CONCAT 函数未实现错误

java - 独立 Jython : Import Error (Apache-POI)

java - 无法从 STRING 单元格错误中获取 NUMERIC 值

java - 将随机值模拟到对象中

apache-poi - apache POI中HSSFWorkbook和Workbook的区别

java - Webdriver隐式等待动态ID

java - 调用 moveToFirst() 时光标抛出 NullPointerException

excel - spark-excel 数据类型问题

java - 为什么 Stream.mapToInt 不处理 NullPointerExceptions?

javascript - jQuery getJSON 方法无响应