excel poi: apply foreground color to blank cells

廉价感情. 提交于 2019-12-12 02:13:50

问题


I want to use poi to set all cells of my excel file to a certain color. however, i keep on getting a nullpointer exception for blank cells. This is what i have so far:

        HSSFWorkbook workBook = new HSSFWorkbook();
        HSSFCellStyle whiteFG = workBook.createCellStyle();
        whiteFG.setFillForegroundColor(HSSFColor.AQUA.index);
        whiteFG.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

        //each row has 20 columns
        int numColumns = 20;

        for (int colNum = 0 ; colNum < numColumns ; colNum++){  

            HSSFCell cell = row.getCell((short)colNum); 

            if (cell != null){
                cell.setCellStyle(whiteFG);
            }

            else if ( "".equals(cell.getStringCellValue()) ){       
                cell.setCellStyle(whiteFG);
            } 

                            else () {
                                 cell.setCellStyle(whiteFG);
                            }

any advice on how i can color the blank cells?


回答1:


Your code can not even compile.

But the reason you getting a NullPointerException, is because this code

if (cell != null){
   cell.setCellStyle(whiteFG);
}
else if ( "".equals(cell.getStringCellValue()) ){       
    cell.setCellStyle(whiteFG);
}

All non-null cell will enter the first condition, so the only cell that enter the second condition is null.


*UPDATE : answer the comment *

I assume you want to create a new xls file with colored cell. However, your code miss a point - A new created Workbook dose not contains any sheet/row/cell, you have to create one by yourself.

Here is an example I wrote.

HSSFWorkbook workBook = new HSSFWorkbook();
HSSFCellStyle style = workBook.createCellStyle();
style.setFillForegroundColor(HSSFColor.BROWN.index);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);

HSSFSheet sheet = workBook.createSheet();
int numRow = 20;
int numCol = 20;

for (int rowIndex = 0; rowIndex < numRow; rowIndex++) {
    HSSFRow row = sheet.createRow(rowIndex);
    for (int colIndex = 0; colIndex < numCol; colIndex++) {
        HSSFCell cell = row.createCell(colIndex);
        cell.setCellStyle(brownBG);
    }
}

FileOutputStream fos = new FileOutputStream("test.xls");
workBook.write(fos);
fos.flush();
fos.close();
System.out.println("done");

The code you wrote use getCell(index) to retrieve cells from a row, this method will only return a null when a you're editing a new xls file.



来源:https://stackoverflow.com/questions/8440119/excel-poi-apply-foreground-color-to-blank-cells

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!