by Nathan

엑셀 업로드(gradle, poi3.7) 본문

Programming/JAVA

엑셀 업로드(gradle, poi3.7)

넷쓴 2018. 7. 30. 13:35

build.gradle

1
2
compile ('org.apache.poi:poi:3.7')
compile ('org.apache.poi:poi-ooxml:3.7')
cs



js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var formData = new FormData($("#formId")[0]);
$.ajax({
    type : 'post',
    url : "/excelupload",
    data : formData,
    processData : false,
    contentType : false,
    success : function(html) {
        alert("파일 업로드를 성공하였습니다.");
    },
    error : function(error) {
        alert("파일 업로드에 실패하였습니다.");
        console.log(error);
        console.log(error.status);
    }
});
cs




Controller

1
2
3
4
5
6
@PostMapping(value="/excelupload")
public String createExcelCustomer(VO vo, MultipartHttpServletRequest multi) throws JsonParseException, JsonMappingException, IOException, BindException {
    
    service.insertExcelData(vo, multi);
    return "success";
}
cs



Service

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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
@SuppressWarnings("unchecked")
public int insertExcelData(Vo vo, MultipartHttpServletRequest multi) {
    int result = 0// 최종 업로드결과
    
    Map<StringString> resMap = new HashMap<StringString>(); // 엑셀업로드 결과리턴(key:파일명, value:파일경로)
    resMap = fm.filesUpload(multi, uploadsRoot + "/static/upload/test/"); // 엑셀파일 업로드 경로
    String filePath = ""// 엑셀파일경로+파일명+확장자
    for(String key : resMap.keySet()){
        filePath= resMap.get(key);
        List<CustomerDetail> resultList = new ArrayList();
        Long customerNo = customerRepository.getSequence(vo); // 고객번호 획득
        
        try {
            FileInputStream fis = new FileInputStream(filePath);
            XSSFWorkbook workbook = new XSSFWorkbook(fis); // 엑셀 workbook
            XSSFSheet sheet = workbook.getSheetAt(0);      // 해당 Sheet
            int rows = sheet.getPhysicalNumberOfRows();    // 해당 Sheet의 row수
            for (int rowIndex=1; rowIndex<rows; rowIndex++) { // row=0은 헤더이므로 1부터 시작
                
                XSSFRow row = sheet.getRow(rowIndex); // 현재 row정보
                if (row != null) {
                    int cells = row.getPhysicalNumberOfCells(); // 한 row당 cell개수
                    
                    /*
                     * list에 담을 현재row정보를 저장할 vo생성
                     */
                    CustomerDetail vo = new CustomerDetail();
                    vo.setStrCd(vo.getStrCd());               // 코드(항상같은정보)
                    vo.setCustNo(Long.toString(customerNo));  // 번호(+1증가)
                    customerNo=customerNo+1;
                    vo.setStat("Y");                          // 여부
                    
                    String value = "";
                    for (int columnIndex=0; columnIndex<cells; columnIndex++) {
                        XSSFCell cell = row.getCell(columnIndex); // 셀에 담겨있는 값을 읽는다.
                        if(cell != null){
                            switch (cell.getCellType()) { // 각 셀에 담겨있는 데이터의 타입을 체크하고, 해당 타입에 맞게 가져온다.
                            case HSSFCell.CELL_TYPE_NUMERIC:
                                value = cell.getNumericCellValue() + "";
                                break;
                            case HSSFCell.CELL_TYPE_STRING:
                                value = cell.getStringCellValue() + "";
                                break;
                            case HSSFCell.CELL_TYPE_BLANK:
                                value = "";
                                break;
                            case HSSFCell.CELL_TYPE_ERROR:
                                value = cell.getErrorCellValue() + "";
                                break;
                            }
                            
                            switch (columnIndex) {
                            case 0 : vo.setCol1(value);    // 컬럼1
                                break;
                            case 1 : vo.setCol2(value);    // 컬럼2
                                break;
                            case 2 : vo.setCol2(value);    // 커럼3
                                break;
                            case 3 : vo.setCol3(value);    // 컬럼4
                                break;
                            }
                        }
                    } // 현재row vo에 set 완료
                    // vo 검증로직은 여기
                    resultList.add(vo); // 검증된 vo 리스트에 추가
                }
                
                // 엑셀 전체row수가 500이상인 경우,
                if(rows > 500){
                    if(resultList.size() >= 500){ // 500건 단위로 잘라서 DB INSERT
                        result = customerRepository.insertExcel(resultList);
                        FTKAssert.isTrue(result >= 1"엑셀 업로드중 오류가 발생하였습니다.");
                        resultList = new ArrayList<>();
                    }
                }
                
            } // row
            
            // 엑셀 전체row수가 500이하인 경우,
            if(rows <= 500){ // 한꺼번에 DB INSERT(LIST size는 반드시 500이하임)
                result = customerRepository.insertExcel(resultList);
                FTKAssert.isTrue(result >= 1"엑셀 업로드중 오류가 발생하였습니다.");
            }
            
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return result;
}
cs



filesUpload 함수

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
public Map filesUpload(MultipartHttpServletRequest multi, String uploadPaths) {
    String strToday = new SimpleDateFormat("yyyyMMdd").format(Calendar.getInstance().getTime());
    String path = uploadPaths + strToday+"/"// 저장 경로 설정
    
    String newFileName = ""// 업로드 되는 파일명
    File dir = new File(path);
    if(!dir.isDirectory()){
        dir.mkdir();
    }
    
    Iterator<String> files = multi.getFileNames();
    Map<StringString> resMap = new HashMap<StringString>();
    String fileName = "";
    while(files.hasNext()){
        String uploadFile = files.next();
        MultipartFile mFile = multi.getFile(uploadFile);
        fileName = mFile.getOriginalFilename();
        newFileName = System.currentTimeMillis()+"."+fileName.substring(fileName.lastIndexOf(".")+1);
        try {
            mFile.transferTo(new File(path+newFileName));
            resMap.put(newFileName, path+newFileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    return resMap;
}
cs




'Programming > JAVA' 카테고리의 다른 글

엑셀 다운로드(gradle, poi3.7)  (0) 2018.07.30
HTTP request  (0) 2017.03.20
StringTokenizer  (0) 2017.03.17
Bubble sort  (0) 2017.03.17
request.getRemoteAddr() ipv4로 받기  (0) 2016.06.13
Comments