코딩 관련/Java
[JAVA] excel 읽기
메리짱123
2021. 8. 23. 13:45
반응형
의존성 추가
dependencies {
implementation 'org.apache.poi:poi:3.15'
implementation 'org.apache.poi:poi-ooxml:3.15'
implementation 'commons-io:commons-io:2.4'
}
열이 세 개인 파일을 읽으려 한다.
excel 읽는 메소드
public JSONArray readExcel(MultipartFile excelFile) {
JSONArray jsonArray = new JSONArray();
try{
XSSFWorkbook workbook = new XSSFWorkbook(excelFile.getInputStream());
XSSFSheet sheet;
XSSFRow curRow;
XSSFCell curCell;
/////////첫번째 시트 읽기
sheet = workbook.getSheetAt(0);
/////////행의 개수
int rownum = sheet.getLastRowNum();
/////////첫 행은 컬럼명이므로 두번째 행인 index1부터 읽기
for(int rowIndex=1;rowIndex<=rownum;rowIndex++){
/////////현재 index의 행 읽기
curRow = sheet.getRow(rowIndex);
/////////현재 행의 cell 개수
int cellnum = curRow.getLastCellNum();
/////////엑셀 데이터를 넣을 json object
JSONObject data = new JSONObject();
for(int cellIndex =0; cellIndex<cellnum;cellIndex++){
System.out.println(rowIndex+"행 "+cellIndex+"열의 값 : " + curRow.getCell(cellIndex));
switch(cellIndex){
case 0 : { /////////첫번째 열 값
data.put("번호",curRow.getCell(cellIndex).getStringCellValue());
};break;
case 1 : { /////////두번째 열 값
data.put("이름",curRow.getCell(cellIndex).getStringCellValue());
};break;
case 2 : { /////////세번째 열 값
data.put("주소",curRow.getCell(cellIndex).getStringCellValue());
}break;
}
}
jsonArray.add(data);
}
return jsonArray;
}catch(Exception e){
System.out.println("ERROR : " + e);
return jsonArray;
}
}
반응형