[SPRING/JAVA] Apache POI를 이용한 Excel 업로드
본문 바로가기

Web 개발/Java, SpringBoot, JPA

[SPRING/JAVA] Apache POI를 이용한 Excel 업로드

728x90
반응형

 

Apache POI 를 이용하여 XLSX형식으로 된 파일 데이터를 읽어오는 예제입니다.

 

1. HTML을 이용하여 파일을 입력 받습니다.

<form action="/upload">
  <input type="file" name="excelFile" accept=".xls,.xlsx">
  <input type="submit">
</form>

 

 

2. Controller를 통해 파일을 받아와서

    파일내에 있는 데이터를 읽어옵니다.

/**
* xlsx형식의 데이터 업로드
*/
@PostMapping("/upload")
public String uploadData(@RequestParam(value = "excelFile", required = true) MultipartFile file) {
	// XSSFWorkbook 파일 열기
    InputStream is = file.getInputStream();
    // 해당파일 XSSFWorkbook로 받기
    XSSFWorkbook workbook = new XSSFWorkbook(is);
    // 0번째 시트 열기
    XSSFSheet sheet = workbook.getSheetAt(0);
    
    // 0번째줄 읽기
    XSSFRow row = sheet.getRow(0);
    // 0번째줄 1번째행을 String형으로 변환
    row.getCell(1).setCellType(CellType.STRING);
    // 0번째줄 1번째행의 값을 String으로 가져옴
    String strData = row.getCell(1).getStringCellValue();
    
    // 2번째줄 3번째행의 숫자값 읽기
    XSSFRow row2 = sheet.getRow(2);
    Double fdata = row2.getCell(3).getNumericCellValue();
    
    // 2번째줄 4번째행의 날짜값 읽기
    Date date = row2.getCell(4).getDateCellValue();    

}

 

 

(내용추가)

3. 입력된 형식 그대로 가져오기

DataFormatter dataFormatter = new DataFormatter();
String str = dataFormatter.formatCellValue(row.getCell(startColPos+5));
dto.setStrData(str);

숫자로 입력된 값을 String형으로 변경하여 가져올 경우

값이 변경되는 오류가 발생하였다.

예) 3.01 -> 3.0100000008

따라서 위와 같이 입력된 형식 그대로 값을 가져와서 읽어서 저장하였다.

 

 

 

728x90
반응형