2011-12-09 2 views
0

poi를 사용하여 내 엑셀 파일의 모든 셀을 특정 색으로 설정하고 싶습니다. 그러나 빈 셀에 대해 nullpointer 예외가 계속 발생합니다. 이것은 내가 지금까지 가지고있는 것입니다 :엑셀 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

코드를 컴파일 할 수도 없습니다. 이 코드

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

이 NULL이 아닌 모든 셀이 첫 번째 조건을 입력하기 때문에

은 그러나 당신이 NullPointerException를 얻는 이유는, 그래서 두 번째 조건을 입력하는 유일한 세포는 null입니다.


* 업데이트 : 난 당신이 색깔의 세포로 새 XLS 파일을 생성한다고 가정 주석 *

에 응답합니다. 그러나 코드에서 한 가지 빠뜨린 점이 있습니다 - 새로 만든 Workbook에는 시트/행/셀이 포함되어 있지 않으므로 혼자 작성해야합니다.

다음은 내가 작성한 예입니다. 새 XLS 파일을 편집 할 때

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를 반환합니다.

관련 문제