본문 바로가기

미역/자바

엑셀 시트 읽어오기

//우선 엑셀파일 경로를 읽어온다
URL resource = yourJavaFile.class.getResource("/yourFolder/excels/file.xlsx");
String filePath = resource.getFile();

//파일 읽기
FileInputStream file = new FileInputStream(filePath);
XSSFWorkbook workbook = new XSSFWorkbook(file); 

List<Map> sheetLst = new ArrayList<Map>();
List<String> columnNmLst = new ArrayList<String>(); 
int rowindex = 0; 
int columnindex = 0; //컬럼명이 첫번째 줄에 있을 거라고 가정

//시트 가져오기, 첫번째 시트만 사용하니까 0 
XSSFSheet sheet = workbook.getSheetAt(0); 

//시트의 행의 수 
int rows = sheet.getPhysicalNumberOfRows();

//columnNmLst에 컬럼명 저장
XSSFRow columNmRow = sheet.getRow(rowindex); 
if(columNmRow != null){ 
    int lastCellIndex = columNmRow.getLastCellNum(); //마지막 컬럼 인덱스
    for(columnindex=0; columnindex<=lastCellIndex; columnindex++){
        XSSFCell cell = columNmRow.getCell(columnindex); 
        String columNm = _getCellForString(cell);
        if(columNm == null) {continue;} //컬럼명이 빈값일 경우를 위한 널체크
        else {
            columnNmLst.add(columNm);
        }
    }
}

//sheetLst에 엑셀시트 정보 저장
for(rowindex=1; rowindex<rows; rowindex++){  
    XSSFRow row = sheet.getRow(rowindex); //행을 읽는다
    if(row != null){
        sheetLst.add(new HashMap<String, String>());
        for(columnindex=0; columnindex<columnNmLst.size(); columnindex++){  
            XSSFCell cell = row.getCell(columnindex); //셀을 읽는다
            String value = _getCellForString(cell);
            if(value == null){ continue; } //셀이 빈값일 경우를 위한 널체크
            else{
                sheetLst.get(rowindex-1).put(columnNmLst.get(columnindex), value);
            }
        }
    }
}

 

// XSSFCell은 값의 타입별로 값을 읽는 함수가 달라서 각 셀마다 적절한 함수로 값을 읽어내야 한다
private String _getCellForString(XSSFCell cell) {
    String value = "";

    if(cell==null){ return null; }
    else{ //타입별로 내용 읽기 
        switch (cell.getCellType()){ 
            case XSSFCell.CELL_TYPE_FORMULA: 
                value=cell.getCellFormula(); 
                break; 
            case XSSFCell.CELL_TYPE_NUMERIC: 
                value=cell.getNumericCellValue()+""; 
                break; 
            case XSSFCell.CELL_TYPE_STRING: 
                value=cell.getStringCellValue()+""; 
                break; 
            case XSSFCell.CELL_TYPE_BLANK: 
                value=cell.getBooleanCellValue()+""; 
                break;
            case XSSFCell.CELL_TYPE_ERROR: 
                value=cell.getErrorCellValue()+""; 
                break; 
        }

        return value;
    }
}

 

'미역 > 자바' 카테고리의 다른 글

@RequestParam / @RequestBody / @ModelAttribute  (0) 2022.06.13
[파이썬] 소수 구하기  (0) 2022.04.22
Map.Entry  (0) 2022.01.20
Optional에 대하여  (0) 2021.12.16
StringBuilder  (0) 2021.12.01