본문 바로가기
Programming/Java

[Java] 엑셀 파일 읽고 쓰기 (1탄)

by 도낙원 2018. 7. 15.
반응형

  엑셀 파일 읽고 쓰기

이번에 프로젝트를 하면서 쓰게된 엑셀 파일을 읽고 쓰는 방법에 대하 포스팅해보려고 합니다. 이전에는 주로 띄어쓰기나 콤마( , )로 구분된 텍스트 파일을 읽어서 데이터를 처리하거나 반대로 쓰는 것을 했었습니다. 이번에 엑셀 파일로 저장된 데이터를 사용하게 되었고 이전에 방식으로는 지겨우니 엑셀로 바로 처리하는 것을 한번 배워보도록 하겠습니다.


   준비물 

엑셀 파일을 읽고 쓰려고 한다면 필요한 것이 있습니다.  아파치 제단(다운로드)에서 제공하는 라이브러리를 다운 받아야 합니다. 구글에서 아파치 POI를 검색하면 많은 정보가 나옵니다. 

이곳에서 일단 zip 파일을 다운 받아 압축을 풀고 라이브러리를 추가해주시면 됩니다.


다운로드(클릭)




라이브러리 추가(자바)

프로젝트 우클릭 -> Build Path -> Configure Build Path 로 들어갑니다.

그리고 압축을 푼 파일에 들어가면 해당하는 jar파일이 있습니다.

그 파일들을 모두 추가해주시면 됩니다.     



라이브러리 추가(이외 방법)

또 다른 방법으로는 Maven에 추가하셔도 됩니다.

pom.xml 파일 안에 아래를 복사해 붙여 넣기 하시면 됩니다.        


처리할 데이터

저는 필요한 데이터가 영화상영관에 관련된 데이터 입니다. 어떤 데이터를 사용해도 상관없습니다. 영화진흥위원회에서 제공해주는 우리나라에 있는 모든 영화상영관 정보입니다. 다른 걸로 해도 상관없습니다. 대신 xls 파일인지 xlsx확인하셔야 합니다. 엑셀 2007이후로 저장된 것은 xlsx 파일이고 그 이전에는 xls 파일입니다.  그 부분만 확인하시면 됩니다.  저는 xls파일입니다.




  코드 

일단 저는 데이터를 읽고 그 데이터를 사용할 수 있도록 가공하고 새로운 엑셀 파일에 저장까지 할 계획입니다. 원래는 가공하고 바로 DB로 저장시켜도 되지만 이때 아니면 해볼 기회가 없을 것 같아서 전부 한번 해보겠습니다.


theaterVo

필요한 데이터를 getter/ setter를 이용해 저장하고 불러올 수 있게 할 것입니다.

제가 필요한 정보는 영화상영관코드 / 브랜드번호 / 영화상영관명 / 주소 / x 좌표 / y 좌표

제일 마지막의 좌표는 제가 필요한 부분이라 신경안쓰셔도 됩니다. 간단하게 그 상영관에 대한 주소의 좌표입니다.

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
 
public class theaterVo {
 
    private int theaterno;
    private int brandno;
    private String theatername;
    private String theateraddress;
    private String theaterxgps;
    private String theaterygps;
 
    public int getBrandno() {
        return brandno;
    }
 
    public void setBrandno(int brandno) {
        this.brandno = brandno;
    }
 
    public int getTheaterno() {
        return theaterno;
    }
 
    public void setTheaterno(int theaterno) {
        this.theaterno = theaterno;
    }
 
    public String getTheatername() {
        return theatername;
    }
 
    public void setTheatername(String theatername) {
        this.theatername = theatername;
    }
 
    public String getTheateraddress() {
        return theateraddress;
    }
 
    public void setTheateraddress(String theateraddress) {
        this.theateraddress = theateraddress;
    }
 
    public String getTheaterxgps() {
        return theaterxgps;
    }
 
    public void setTheaterxgps(String theaterxgps) {
        this.theaterxgps = theaterxgps;
    }
 
    public String getTheaterygps() {
        return theaterygps;
    }
 
    public void setTheaterygps(String theaterygps) {
        this.theaterygps = theaterygps;
    }
 
    @Override
    public String toString() {
        return "theaterVo [theaterno=" + theaterno + ", brandno=" + brandno + ", theatername=" + theatername
                + ", theateraddress=" + theateraddress + ", theaterxgps=" + theaterxgps + ", theaterygps=" + theaterygps
                + "]";
    }
 
}
 
cs


readeExcel 메소드

2007버전 이후는 XSSFWorkbook을 사용하시면 되며 밑에 현재 sheet와 같은 것은 앞에 H->X로만 바꿔주면 사용이 가능하실 겁니다.


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
    public ArrayList<theaterVo> readexcel() {
        String path = "./TheaterList.xls"// 읽을 파일 경로
        ArrayList<theaterVo> theaterlist = new ArrayList<theaterVo>(); // 데이터를 담을 list
 
        try {
            File file = new File(path);
            FileInputStream inputStream = new FileInputStream(file);
            HSSFWorkbook hworkbook = new HSSFWorkbook(inputStream); // 2007 이전 버전(xls파일)
            //XSSFWorkbook xworkbook = new XSSFWorkbook(inputStream); // 2007 이후 버전(xlsx파일)
            
            HSSFSheet curSheet; // 현재 sheet
            HSSFCell curCell; // 현재 cell
            HSSFRow curRow; // 현재 row
 
            int sheetNumber = hworkbook.getNumberOfSheets(); // 엑셀 Sheet 총 갯수
            //System.out.println("sheetNumber : "+sheetNumber);  Sheet 갯수 확인
            while (sheetNumber != 0) {
                sheetNumber--;
 
                curSheet = hworkbook.getSheetAt(sheetNumber);
                int row = curSheet.getPhysicalNumberOfRows();
                //System.out.println(row); 현재 sheet의 row 갯수 확인
                for (int i = 1; i < row; i++) {
                    theaterVo vo = new theaterVo();
                    curRow = curSheet.getRow(i);
                    
                    // vo의 setter를 이용해 담고 있습니다.
                    // 여기서는 그대로 담는 것이 아니라 자료형에 맞춰서 형변환을 해주셔야 합니다.
                    vo.setTheaterno(Integer.valueOf(String.valueOf(curRow.getCell(2))));
                    vo.setTheatername(String.valueOf(curRow.getCell(3)));
                    vo.setTheateraddress(String.valueOf(curRow.getCell(18)));
                    // 아래의 brandno는 필요한 부분이라 따로 제가 만든 메소드 이기 떄문에 아래 2줄은 빼셔도 됩니다.
                    int brandno = TransferAddress.brandno(String.valueOf(curRow.getCell(14)));
                    vo.setBrandno(brandno);
 
                    theaterlist.add(vo);
                }
            }
 
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
 
        return theaterlist;
    }
cs


cell과 row의 시작은 0 부터 입니다. 

그래서 제일 위에 제목은 필요 없어서 for문을 1부터 시작했습니다.


이제 실행시켜 보도록 하겠습니다.



정상적으로 찍어내고 있습니다.

이렇게 쉽게 읽어들일 수 있었습니다. 

간단하게 읽어서 콘솔에 찍는 것만 했기 때문에 많이 어려운 부분은 없을 것입니다.

한번 따라 해보시고 자기 데이터에 맞게 사용하시면 되겠습니다.

다음 포스팅에서는 새로운 엑셀 파일로 저장을 할 수 있도록 해보겠습니다.


아래는 모든 코드 입니다.

반응형
사업자 정보 표시
난길샵 | 박현숙 | 경상북도 성주군 월항면 수죽길 98길 | 사업자 등록번호 : 256-07-01668 | TEL : 010-9909-8420 | Mail : skr04@naver.com | 통신판매신고번호 : 제2020-경북성주-52호 | 사이버몰의 이용약관 바로가기

댓글