2017-11-24 7 views
-1

아파치 POI 라이브러리를 사용하여 엑셀 시트에서 데이터를 가져옵니다. 노란 부분이 강조 표시된 엑셀 시트를 첨부했습니다. 엑셀 시트에서 모든 데이터를 추출하려고하는데 강조 표시된 부분의 데이터를 가져 오지 못했습니다. 이 셀에 액세스하려고하면 널 포인터 예외가 발생합니다.값이있는 셀에 액세스 할 때 Null Pointer Exception이 발생합니까?

샘플 문서 : Document

샘플 코드입니다.

FileInputStream inputStream = 새 FileInputStream (파일);

 Workbook workbook = new XSSFWorkbook(inputStream); 
     Sheet firstSheet = workbook.getSheetAt(0); 
     Iterator<Row> iterator = firstSheet.iterator(); 

     while (iterator.hasNext()) { 
      Row nextRow = iterator.next(); 
      Iterator<Cell> cellIterator = nextRow.cellIterator(); 

      while (cellIterator.hasNext()) { 
       Cell cell = cellIterator.next(); 

       System.out.print(cell.getStringCellValue()); 
       System.out.print(","); 
      } 
      System.out.println(); 
     } 

     workbook.close(); 
     inputStream.close(); 

위의 프로그램을 실행하면 일부 필드가 Excel 시트 (강조 표시된 부분)에서 추출되지 않습니다. 명시 적으로 해당 셀에 액세스하려고하면 널 포인터 예외가 발생합니다.

+1

가능한 복제 (https://stackoverflow.com/ [NullPointerException이 무엇인가, 나는 그것을 해결 어떻게?] 질문/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) –

+0

@JoeC 무엇이 NullPointerException인지 압니다. 질문을주의 깊게 읽으십시오. 셀에 문자열 값이 있지만 액세스하려고 할 때 널 포인터 예외가 발생합니다. Apache Poi는 셀에 값이 없을 때 널 포인터 예외를 발생시킵니다. – Tyson

+0

어떤 코드 라인이 NPE를 던집니까? stacktrace를 보여주십시오. –

답변

0

동작을 재현 할 수 없습니다. System.out.print(cell.getStringCellValue());이 NPE를 throw하면 cellnull이어야합니다. 그러나 Row.cellIterator은 현재 셀에만 반복되고 이 아닌null이므로 코드에 따라 은 null이 될 수 없습니다.

SAMPLE.xlsx을 다운로드하고 코드를 Busy Developers' Guide - Getting the cell contents에서 사용했습니다. 이 코드는 문제없이 모든 셀을 읽습니다. 결과의

import org.apache.poi.ss.usermodel.*; 
import org.apache.poi.ss.util.*; 

import java.io.FileInputStream; 

class ReadExcelExampleDataFormatter { 

public static void main(String[] args) throws Exception { 

    Workbook wb = WorkbookFactory.create(new FileInputStream("SAMPLE.xlsx")); 

    DataFormatter formatter = new DataFormatter(); 
    FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator(); 

    Sheet sheet = wb.getSheetAt(0); 
    for (Row row : sheet) { 
    for (Cell cell : row) { 
    CellReference cellRef = new CellReference(row.getRowNum(), cell.getColumnIndex()); 
    System.out.print(cellRef.formatAsString()); 
    System.out.print(" - "); 
    // get the text that appears in the cell by getting the cell value and applying any data formats (Date, 0.00, 1.23e9, $1.23, etc) 
    String text = formatter.formatCellValue(cell); 
    System.out.println(text); 
    } 
    } 
    wb.close(); 
} 
} 

부 (첫 번째 노란색 범위)의

A15 - Report 
Summary 
B15 - Real Estate 
C15 - Count 
D15 - 3 
E15 - 0 
F15 - 2 
A16 - 
B16 - 
C16 - Balance 
D16 - $94,263.00 
E16 - $0.00 
F16 - $94,263.00 
A17 - 
B17 - 
C17 - Current 
D17 - 2 
E17 - 0 
F17 - 2 
A18 - 
B18 - 
C18 - Delinquent 
D18 - 0 
E18 - 0 
F18 - 0