Excel的POI:适用前景色为空白单元格 [英] excel poi: apply foreground color to blank cells

查看:271
本文介绍了Excel的POI:适用前景色为空白单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用POI到我的Excel文件中的所有小区设置为一定的颜色。不过,我不断获取的空白单元格一个空指针异常。这是我迄今为止:

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?

推荐答案

您code甚至不能编译。

Your code can not even compile.

但你得到原因的 NullPointerException异常,是因为这个code

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);
}

所有非空单元格将进入第一个条件,使进入第二个条件的唯一细胞是

*的更新:回答注释*

我假设你想创建一个彩色电池新xls文件。但是,您的code错过任何一个点 - 新创建工作簿剂量包含任何表/行/单元格,你必须创建一个自己。

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");

在code你写使用 getCell(指数)来从行获取细胞,这种方法只会返回一个当你编辑一个新的xls文件。

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.

这篇关于Excel的POI:适用前景色为空白单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆