excel poi:将前景色应用于空白单元格 [英] excel poi: apply foreground color to blank cells
问题描述
我想使用 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?
推荐答案
你的代码甚至无法编译.
Your code can not even compile.
但是你得到 NullPointerException
的原因是因为这段代码
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);
}
所有非空单元格都会进入第一个条件,所以唯一进入第二个条件的单元格是null
.
All non-null cell will enter the first condition, so the only cell that enter the second condition is null
.
*UPDATE : 回复评论 *
我假设您想创建一个带有彩色单元格的新 xls 文件.但是,您的代码遗漏了一点 - 新创建的 Workbook
不包含任何工作表/行/单元格,您必须自己创建一个.
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.
这是我写的一个例子.
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");
您编写的代码使用 getCell(index)
从一行中检索单元格,此方法只会在您编辑新的 xls 文件时返回 null
.
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屋!