봉봉의 개인 블로그

2017-11-03(엑셀 poi read 관련) 본문

입사후 공부한내용

2017-11-03(엑셀 poi read 관련)

봉봉이네 2017. 11. 3. 15:17

엑셀 파일의 컬럼 항목과 동일하게 구성된 Vo를 만들어준다.


CustomerExcelReader Class

파일의 경로를 입력받아 List<CustomerVo>의 행태로 리턴해주는 메소드를 구현

실제로 xsl이나,xslx나 로직의 차이는 없고, 메소드 역시 동일하다. 클래스 명만 변경하여 주면 된다.

주요 요점은 Workbook, Sheet, Row, Cell의 순서로 엑셀 파일의 내용을 탐색하는데 있다.

*xsl : HSSFWorkbook -> HSSFSheet -> HSSFRow -> HSSFCell -> 값 획득

*xslx : XSSFWorkbook -> XSSFSheet -> XSSFRow -> XSSFCell -> 값 획득


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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
// xls 파일을 분석하여 List<CustomerVo> 객체로 반환 
// @param filePath
// @return
 
@supperssWarnings("resource")
public List<CustomerVo> xlsToCustomerVoList(String filePath){
    //반환할 객체를 생성
    List<CustomerVo> list = new ArrayList<CustomerVo>();
 
    FileInputStream fis = null;
    HSSFWorkbook workbook = null;
 
    try{
        fis = new FileInputStream(filePath);
        // HSSFWorkbook 은 엑셀 파일 전체 내용을 담고 있는 객체
        workbook = new HSSFWorkbook(fis);
 
        //탐색에 사용할 Sheet, Row, Cell 객체
        HSSFSheet curSheet;
        HSSFRow curRow;
        HSSFCell curCell;
        CustomerVo vo;
 
        //Sheet 탐색 for 문
        for(int sheetcount = 0 ; sheetcount < workbook.getNumberofSheets() ; sheetcount++){
            //현재 Sheet 반환
            curSheet = workbook.getSheetAt(sheetcount);
            //row xkator for 문
            for(int rowcount = 0 ; rowcount < curSheet.getPhysicalNumberOfRows() ; rowcount++){
                //row 0은 헤더 정보이기 때문에 무시
                if(rowcount != 0){
                    //현재 row 반환
                    curRow = curSheet.getRow(rowcount);
                    vo = new CustomerVo();
                    String value;
 
                    //row 첫번째 cell 값이 비어있지 않은 경우만 cell 탐색
                    if(!"".equals(curRow.getCell(0).getStringCellValue())){
                        //cell 탐색 for 문
                        for(int cellcount = 0 ; cellcount < curRow.getphysicalNumberOfCells() ; cellcount++){
                            curCell = curRow.getCell(cellcount);
 
                            if(true){
                                value = "";
                                //cell 스타일이 다르더라도 String 으로 반환 받음
                                switch (curCell.getCellType()){
                                case HSSFCell.CELL_TYPE_FORMULA:
                                    value = curCell.getCellFormula();
                                    break;
                                case HSSFCell.CELL_TYPE_NUMERIC:
                                    value = curCell.getNumericCellValue()+"";
                                    break;
                                case HSSFCell.CELL_TYPE_STRING:
                                    value = curCell.getStringCellValue()+"";
                                    break;
                                case HSSFCell.CELL_TYPE_BLANK:
                                    value = curCell.getBooleanCellValue()+"";
                                    break;
                                case HSSFCell.CELL_TYPE_ERROR:
                                    value = curCell.getErrorCellValue()+"";
                                    break;
                                default:
                                    value = new String();
                                    break;
                                }
                                //현재 column index에 따라서 Vo에 입력
                                switch (cellcount){
                                case 0//ID
                                    vo.setCustId(value);;
                                    break;
                                case 1//Name
                                    vo.setCustId(value);;
                                    break;
                                case 2//Age
                                    vo.setCustId(value);;
                                    break;
                                case 3//Email
                                    vo.setCustId(value);;
                                    break;
                                default:
                                    break;
                                }
                            }
                        }
                        //cell 탐색 이후 vo 추가
                        list.add(vo);
                    }
                }
            }
        }
    }catch(FileNotFoundException e){
        e.printStackTrace();
    }catch(IOException e){
        e.printStackTrace();
    }finally{
        try{
            //사용한 자원은 finally에서 해제
            if(workbook != null) workbook.close();
            if(fis != null) fis.close();
        }catch(IOException e){
            e.printStackTrace();
        }
    }
    return list;
}
// xlsx 파일을 분석하여 List<CustomerVo> 객체로 반환 
// @param filePath
// @return
public List<CustomerVo> xlsxToCustomerVoList(String filePath){
    //반환할 객체를 생성
    List<CustomerVo> list = new ArrayList<CustomerVo>();
    FileInputStream fis = null;
    XSSFWorkbook workbook = null;
    try{
        fis = new FileInputStream(filePath);
        // HSSFWorkbook 은 엑셀 파일 전체 내용을 담고 있는 객체
        workbook = new XSSFWorkbook(fis);
        //탐색에 사용할 Sheet, Row, Cell 객체
        XSSFSheet curSheet;
        XSSFRow curRow;
        XSSFCell curCell;
        CustomerVo vo;
        //Sheet 탐색 for 문
        for(int sheetcount = 0 ; sheetcount < workbook.getNumberofSheets() ; sheetcount++){
            //현재 Sheet 반환
            curSheet = workbook.getSheetAt(sheetcount);
            //row xkator for 문
            for(int rowcount = 0 ; rowcount < curSheet.getPhysicalNumberOfRows() ; rowcount++){
                //row 0은 헤더 정보이기 때문에 무시
                if(rowcount != 0){
                    //현재 row 반환
                    curRow = curSheet.getRow(rowcount);
                    vo = new CustomerVo();
                    String value;
                    //row 첫번째 cell 값이 비어있지 않은 경우만 cell 탐색
                    if(!"".equals(curRow.getCell(0).getStringCellValue())){
                        //cell 탐색 for 문
                        for(int cellcount = 0 ; cellcount < curRow.getphysicalNumberOfCells() ; cellcount++){
                            curCell = curRow.getCell(cellcount);
                            if(true){
                                value = "";
                                //cell 스타일이 다르더라도 String 으로 반환 받음
                                switch (curCell.getCellType()){
                                case HSSFCell.CELL_TYPE_FORMULA:
                                    value = curCell.getCellFormula();
                                    break;
                                case HSSFCell.CELL_TYPE_NUMERIC:
                                    value = curCell.getNumericCellValue()+"";
                                    break;
                                case HSSFCell.CELL_TYPE_STRING:
                                    value = curCell.getStringCellValue()+"";
                                    break;
                                case HSSFCell.CELL_TYPE_BLANK:
                                    value = curCell.getBooleanCellValue()+"";
                                    break;
                                case HSSFCell.CELL_TYPE_ERROR:
                                    value = curCell.getErrorCellValue()+"";
                                    break;
                                default:
                                    value = new String();
                                    break;
                                }
                                //현재 column index에 따라서 Vo에 입력
                                switch (cellcount){
                                case 0//ID
                                    vo.setCustId(value);;
                                    break;
                                case 1//Name
                                    vo.setCustId(value);;
                                    break;
                                case 2//Age
                                    vo.setCustId(value);;
                                    break;
                                case 3//Email
                                    vo.setCustId(value);;
                                    break;
                                default:
                                    break;
                                }
                            }
                        }
                        //cell 탐색 이후 vo 추가
                        list.add(vo);
                    }
                }
            }
        }
    }catch(FileNotFoundException e){
        e.printStackTrace();
    }catch(IOException e){
        e.printStackTrace();
    }finally{
        try{
            //사용한 자원은 finally에서 해제
            if(workbook != null) workbook.close();
            if(fis != null) fis.close();
        }catch(IOException e){
            e.printStackTrace();
        }
    }
    return list;
}
cs

이와 같이 적어줍니다.


MainApplication Class

실제 엑셀 파일 read를 테스트 하여 출력한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public static void main(String[] args){
    CustomerExcelReader excelReader = new CustomerExcelReader();
 
    System.out.println("*****xls*****");
    List<CustomerVo> xlsList = excelReader.xlsToCustomerVoList("c:\\excel\\test.xls");
    printList(xlsLIst);
 
    System.out.println("*****xlsx*****");
    List<CustomerVo> xlsxList = excelReader.xlsToCustomerVoList("c:\\excel\\test.xlsx");
    printList(xlsxLIst);
}
public static void printList(List<CustomerVo> list){
    CustomerVo vo;
    for(int i = 0 ; i < list.size() ; i++){
        vo = list.get(i);
        System.out.println(vo.toString());
    }
}
cs


Comments