반응형

Java에서 excel 파일을 읽을 때 대부분 apache-poi lib를 사용을 할 거예요 저도 poi를 사용하여 구현을 했어요.

compile group: 'org.apache.poi', name: 'poi', version: '4.1.2'
compile group: 'org.apache.poi', name: 'poi-ooxml', version: '4.1.2'

4.1.2 버전을 사용을 했어요.

보통 2003,통합문서 2가지 버전들이 있는데 org.apache.poi.ss.usermodel.WorkbookFactory를 이용하면 포맷 구분 없이 읽을 수 있어요.

 

예를 들어 위 해당하는 문서를 읽을경우를 해볼게요.

//엑셀파일을 넣구 Wookbook를 생성합니다
Workbook workbook = WorkbookFactory.create(file1.getInputStream());

int rowindex = 0;
int cellindex = 0;
//시트 수 (첫번째에만 존재하므로 0을 준다)
//만약 각 시트를 읽기위해서는 FOR문을 한번더 돌려준다
Sheet sheet = workbook.getSheetAt(0);
//행의 수
int rows = sheet.getPhysicalNumberOfRows();
//3번째 row부터 읽기위해 rowindex는 2부터
for (rowindex = 2; rowindex < rows; rowindex++) {
	//행을읽는다
	Row row = sheet.getRow(rowindex);
	
    //row값이 있으면
	if (row != null) {
			//B3부터 데이터 추출
        	//엑셀에 데이터 형식에 따라 get방식이 달르게 가져와야해요 전 전부 일반으로 설정을하고 가져오고 있어요        
        	for (cellindex = 1; cellindex < row.getPhysicalNumberOfCells(); cellindex++) {

			System.out.println(getStringValue(row.getCell(cellindex)));

		}
        
	}
            
}


public static String getStringValue(Cell cell) {
	String rtnValue = "";
	try {
		rtnValue = cell.getStringCellValue();
	} catch (IllegalStateException e) {
		rtnValue = Integer.toString((int) cell.getNumericCellValue());
	} catch (NullPointerException e) {
		rtnValue = "";
	}

	return rtnValue;
}

cell이 늘어남에 따라 row.getCell(1) 2,3,4.... 이렇게 계속할 수 없어 for문을 사용했어요.

 

그럼 B3~F3까지 데이터를 와서 sysout으로 출력을 하고 있어요. 엑셀에 데이터 방식에 따라 cell처리 방식들이 다른데 저는 전부 텍스트 형식으로 지정하고 업로드를 했어요

 

반응형

+ Recent posts