'CSV'에 해당되는 글 1건

  1. 2009.03.02 CSV파일

출처 : http://narrowway.tistory.com/43


CSV파일

Comma Separated Value의 약자로,
데이타를 컴머(,)단위로 잘라서 나열한 파일 형태.

컴머단위로 잘라져 있으므로, 텍스트 파일로도 읽을수 있지만,
엑셀파일로도 바로 읽을수 있다는 장점이 있어서
많은 데이타 관련 소프트웨어에서 사용되고 있다.

1. 자바에서의 구현

    // 파일 다운로드 형식 지정
    res.setContentType("application/octet-stream;charset=Shift_JIS");
    res.setHeader("Content-Disposition","attachment; filename="+selected_Table+"_"+date+".csv");
    PrintWriter out=res.getWriter();

    // 데이타를 DB로 부터 읽어서 CSV로 만드는 과정
      query = "select * from " + selected_Table;
     
      PreparedStatement pstmt = con.prepareStatement(query);
      rs = pstmt.executeQuery();

      String strData = "";
      while(rs.next()){
       
        for(int i=0 ; i < selectedFieldList.length ; i++){
     strData = rs.getString(Integer.parseInt(selectedFieldList[i])+1);
     if(strData==null){strData="";}
      out.print( new String( strData.getBytes("8859_1"),"Shift_JIS") );
            out.print(i<selectedFieldList.length ? "," : "");
        }
        out.print(System.getProperty("line.separator"));
      }

      위와같이 컴마와 System.getProperty("line.separator")를 이용해서 제어가 가능하고,
      문자열처리과정을 일본어의 경우 new String( strData.getBytes("8859_1"),"Shift_JIS")
      처럼 해결해 주면 된다.

2. 주의할 점

     CSV파일의 가장 주의점이라 한다면 데이타 자체에 컴마나 줄바꿈 표시가 들어가 있는 경우로,
     이때는 의도하지 않는 데이타상의 구분이 생겨버리므로,
     향후 엑셀로 읽으려 할때에는 전체 테이블이 깨져버린다.
    
      private String checkDataFormat(String data){

           String returnVal = data;
   
           returnVal = returnVal.replaceAll(","," ");
           returnVal = returnVal.replaceAll("\n"," ");
           returnVal = returnVal.replaceAll("\r"," ");
           returnVal = returnVal.replaceAll("\r\n"," ");
   
           return returnVal;
     }

     와 같은 방법으로 데이타 치환을 해주어야 한다. 

작업노트/JAVA l 2009. 3. 2. 17:03
1 

최근에 올라온 글

최근에 달린 댓글

최근에 받은 트랙백

카테고리

분류 전체보기 (117)
작업노트 (98)
거미줄세상 (12)
쌓기 (1)
책읽기 (0)
Reviews (4)

달력

«   2024/05   »
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
get rsstistory! Tistory Tistory 가입하기!