2011-12-09 45 views
0

我想使用poi將我的excel文件的所有單元格設置爲某種顏色。但是,我一直在爲空白單元格獲取空指針異常。這是我到目前爲止:excel poi:將前景色應用於空白單元格

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

任何意見,我怎麼可以給空白單元格上色?

回答

4

你的代碼甚至無法編譯。

但你得到一個NullPointerException的原因,是因爲這段代碼

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

所有非空單元格將進入第一個條件,從而使進入第二個條件的唯一細胞是null


* 更新:回答我假設你想創建一個彩色小區的新XLS文件的註釋*

。但是,您的代碼錯過了一點 - 新創建的Workbook劑量不包含任何工作表/行/單元格,您必須自行創建一個。

這是我寫的一個例子。

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)從行中檢索細胞的代碼,這種方法只會返回一個null當你正在編輯一個新的xls文件。

相關問題