java poi 엑셀 업로드 excel upload 심플한 방법

2016. 11. 11. 09:57language/java

 

JAVA 에서 Poi 를 이용한 엑셀(excel)을 업로드 하는 방법이다.

 

Spring 3.0 에서 작성되었다.

 

 

엑셀 업로드 요약

1. jsp 에서 엑셀파일 업로드

2. controller 에서 MultipartHttpServletRequest 로 파일을 서버에 저장 (참고)

3. 서버에 저장된 엑셀 파일 경로를 FileInputStream으로 읽어들여서 Workbook 객체로 만듬

4. Workbook 객체로 기본적인 엑셀양식 구조 체크

5. 사용가능한 vo 객체로 데이터 복사

6. 데이터 타입 및 형식 체크(날짜이면 올바른 날짜형식인지 등)

7. 크기체크 (DB에 입력하려면 사이즈체크 필수) (참고)

 

위 7가지 내용중에서 3, 4, 5 에 대한 설명이다.

 

1, 2, 6, 7 은 생략되었다.

 

특히 2번 파일을 업로드 하는 방식은 아래 링크 또는 위 요약에서 '참고' 링크로 이동해서 확인하면 된다.

java poi 엑셀 업로드 excel upload | spring

위 포스팅에 파일을 업로드하는 설명이 있기 때문에 본 포스팅에서는 생략한다.

 

 

위 포스팅과는 다른 방법으로 엑셀을 업로드해보겠다.

 

훨신 심플한 소스이다.

 

위 포스팅도 한번 읽어보면 좋다.

 



 

라이브러리 목록

 commons-io
 poi-3.10-FINAL-20140208.jar
 poi-excelant-3.10-FINAL-20140208.jar
 poi-ooxml-3.10-FINAL-20140208.jar
 poi-ooxml-schemas-3.10-FINAL-20140208.jar
 poi-scratchpad-3.10-FINAL-20140208.jar
 stax-api-1.0.1.jar
 xmlbeans-2.3.0.jar

 

 commons-fileupload

 commons-io 

 

 

해당 소스에서 업로드할 예제 엑셀 양식이다.

 

 1

 관리번호

 정산금액 

 정산날짜 

 

 

 

 2

 1-1

 5000

 2016-05-11 

 

 

 

 3

 1-2

 2000

 2016-11-11

 

 

 

 4

 1-3

 100

 2016-12-10

 

 

 

 

 

* 위 모양의 엑셀을 업로드 했을때의 소스이니 참고

 

 

엑셀 데이터를 추출하는 함수

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
    /**
      * 엑셀 데이터 추출
      * 
      * @param excelFile
      * @return
      * @throws Exception
      */
    private List<TestVO> parseTableExcel(String excelFile) throws Exception {
        List<TestVO> excelVOList = new ArrayList<TestVO>();
 
        try {
            Workbook wbs = WorkbookFactory.create(new FileInputStream(excelFile));
            Sheet sheet = (Sheet) wbs.getSheetAt(0);
 
            int lastCellNum = 0;
 
            for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                if (i == 0) {
                    lastCellNum = row.getLastCellNum();
                    if (lastCellNum != 3) { throw new Exception("양식이 잘못되었습니다."); }
 
                    Cell cell = row.getCell(0);
                    if (!cell.getRichStringCellValue().getString().trim().equals("관리번호")) { throw new Exception("[관리번호] 헤더가 일치 하지 않습니다."
                            + cell.getRichStringCellValue().equals("관리번호")); }
 
                    cell = row.getCell(1);
                    if (!cell.getRichStringCellValue().getString().trim().equals("정산금액")) { throw new Exception("[정산금액] 헤더가 일치 하지 않습니다."
                            + cell.getRichStringCellValue().equals("정산금액")); }
 
                    cell = row.getCell(2);
                    if (!cell.getRichStringCellValue().getString().trim().equals("정산날짜")) { throw new Exception("[정산날짜] 헤더가 일치 하지 않습니다."
                            + cell.getRichStringCellValue().equals("정산날짜")); }
 
                } else {
                    // 필수항목 체크
                    if (StringUtils.isNotEmpty(cellValue(row.getCell(0)))) {
 
                        TestVO excelVO = new TestVO();
                        excelVO.setNo(cellValue(row.getCell(0)));
                        excelVO.setMoney(cellValue(row.getCell(1)));
                        excelVO.setDate(cellValue(row.getCell(2)));
 
                        excelVOList.add(excelVO);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("오류가 있는 데이터가 있습니다." + e.getMessage());
        }
 
        return excelVOList;
    }
 
cs

 

8# : 파라미터로 엑셀파일 경로를 받는다.

12# : 엑셀 파일 경로를 FileInputStream으로 읽어들여서 Workbook 를 만든다.

13# : 엑셀의 첫번째 시트를 꺼낸다.

21# : 셀의 갯수를 세어 일치하지 않으면 오류발생

23# ~ 33# : 셀의 해더 이름을 체크함

37# : 필수항목이 비어있는지 체크함

39# ~ 42# : 엑셀의 내용을 vo에 담는다.

44# : 엑셀내용을 담은 vo 를 List 에 담는다.

 

 

이렇게 작성하고 parseTableExcel 함수를 호출하면 된다.

 

근데 여기서 cellValue 에서 오류가 날 것이다.

 

cellValue 함수는 별도로 구현했다.

 

엑셀 데이터는 셀마다 각각 데이터 포멧이나 유형이 나뉘어져 있다.

그래서 꺼낼때 이 속성에 맞는것을 찾아서 꺼내는것이 중요하다.

예를 들어서 숫자가 들어가있는데 문자타입으러 꺼내려 하면 오류가 난다는 거다.

 



 

엑셀 셀 타입별로 데이터 추출

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
    public String cellValue(Cell cell) {
 
        String value = null;
        if (cell == null) value = "";
        else {
            switch (cell.getCellType()) { //cell 타입에 따른 데이타 저장
            case Cell.CELL_TYPE_FORMULA:
                value = cell.getCellFormula();
                break;
            case Cell.CELL_TYPE_NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    //you should change this to your application date format
                    SimpleDateFormat objSimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    value = "" + objSimpleDateFormat.format(cell.getDateCellValue());
                } else {
                    value = "" + String.format("%.0f", new Double(cell.getNumericCellValue()));
                }
                break;
            case Cell.CELL_TYPE_STRING:
                value = "" + cell.getStringCellValue();
                break;
            case Cell.CELL_TYPE_BLANK:
                //value=""+cell.getBooleanCellValue();
                value = "";
                break;
            case Cell.CELL_TYPE_ERROR:
                value = "" + cell.getErrorCellValue();
                break;
            default:
            }
        }
 
        return value.trim();
    }
cs