반응형

셀 크기 조정 (참고로 자동으로하는거 찾음) ㅠ.ㅠ

for (int i=0;i<temp;i++) //autuSizeColumn after setColumnWidth setting!!
{
sheet.autoSizeColumn(i);
sheet.setColumnWidth(i, (sheet.getColumnWidth(i))+512 ); //이건 자동으로 조절 하면 너무 딱딱해 보여서 자동조정한 사이즈에 (short)512를 추가해 주니 한결 보기 나아졌다.
}

셀 높이 조정

row.setHeight((short)512);

 

반응형
반응형
//통합 문서 생성을을 위한 Workbook인스턴스 생성   
        HSSFWorkbook wb = new HSSFWorkbook();   
           
        //엑셀화일의 새로운 Sheet를 만들어진 Workbook인스턴스에 생성함   
        HSSFSheet sheet1 = wb.createSheet("sheet1");   
           
        //해더부분셀에 스타일을 주기위한 인스턴스 생성   
        HSSFCellStyle cellStyle = wb.createCellStyle();            
        cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);                     //스타일인스턴스의 속성 셑팅           
        cellStyle.setFillForegroundColor(HSSFCellStyle.GREY_25_PERCENT);        //셀에 색깔 채우기   
        cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);   
        cellStyle.setBorderRight(HSSFCellStyle.BORDER_MEDIUM);              //테두리 설정   
        cellStyle.setBorderLeft(HSSFCellStyle.BORDER_MEDIUM);   
        cellStyle.setBorderTop(HSSFCellStyle.BORDER_MEDIUM);   
        cellStyle.setBorderBottom(HSSFCellStyle.BORDER_MEDIUM);   
        HSSFFont font = wb.createFont();                                    //폰트 조정 인스턴스 생성   
        font.setBoldweight((short)700);        
        cellStyle.setFont(font);   
           
        //가운데 정렬과 얇은 테두리를 위한 스타일 인스턴스 생성   
        HSSFCellStyle cellStyle0 = wb.createCellStyle();                           
        cellStyle0.setAlignment(HSSFCellStyle.ALIGN_CENTER);   
        cellStyle0.setBorderRight(HSSFCellStyle.BORDER_THIN);   
        cellStyle0.setBorderLeft(HSSFCellStyle.BORDER_THIN);   
        cellStyle0.setBorderTop(HSSFCellStyle.BORDER_THIN);   
        cellStyle0.setBorderBottom(HSSFCellStyle.BORDER_THIN);   
           
        //얇은 테두리를 위한 스타일 인스턴스 생성   
        HSSFCellStyle cellStyle1 = wb.createCellStyle();           
        cellStyle1.setBorderRight(HSSFCellStyle.BORDER_THIN);   
        cellStyle1.setBorderLeft(HSSFCellStyle.BORDER_THIN);   
        cellStyle1.setBorderTop(HSSFCellStyle.BORDER_THIN);   
        cellStyle1.setBorderBottom(HSSFCellStyle.BORDER_THIN);   
           
        //Sheet에 첫번재 Row(가로열)생성   
        HSSFRow row = sheet1.createRow((short)0);   
        row = sheet1.createRow((short)1);   
       
        // 셀별 위드 정하기 헤더 그리기    
            sheet1.setColumnWidth((short)0, (short)2000);   
            sheet1.setColumnWidth((short)1, (short)5000);   
            sheet1.setColumnWidth((short)2, (short)7000);   
            sheet1.setColumnWidth((short)3, (short)5000);   
            sheet1.setColumnWidth((short)4, (short)3000);   
            sheet1.setColumnWidth((short)5, (short)3000);   
            sheet1.setColumnWidth((short)6, (short)3000);   
                   
       
        // 헤더 그리기    
        HSSFCell cell = row.createCell((short)0);          
        cell.setEncoding(HSSFCell.ENCODING_UTF_16);    
                           
        cell.setCellStyle(cellStyle);   
        cell.setCellValue("계약ID");   
           
        cell = row.createCell((short)1);   
        cell.setEncoding(HSSFCell.ENCODING_UTF_16);   
        cell.setCellStyle(cellStyle);   
        cell.setCellValue("사업자명");   
           
        cell = row.createCell((short)2);   
        cell.setEncoding(HSSFCell.ENCODING_UTF_16);   
        cell.setCellStyle(cellStyle);   
        cell.setCellValue("홈페이지");   
       
        cell = row.createCell((short)3);   
        cell.setEncoding(HSSFCell.ENCODING_UTF_16);   
        cell.setCellStyle(cellStyle);   
        cell.setCellValue("대표전화");   
               
        cell = row.createCell((short)4);   
        cell.setEncoding(HSSFCell.ENCODING_UTF_16);   
        cell.setCellStyle(cellStyle);   
        cell.setCellValue("계약일자");   
           
        cell = row.createCell((short)5);   
        cell.setEncoding(HSSFCell.ENCODING_UTF_16);    
        cell.setCellStyle(cellStyle);   
        cell.setCellValue("개통일자");   
           
        cell = row.createCell((short)6);   
        cell.setEncoding(HSSFCell.ENCODING_UTF_16);   
        cell.setCellStyle(cellStyle);   
        cell.setCellValue("연결일자");          

 

반응형
반응형

클라이언트에서 ajax로 요청했을 때 자료를 손쉽게 파싱하기 위해서 json으로 클라이언트에 던져줄 때가 편할 때가 있습니다. 그래서 손쉽게 json으로 변환하는 라이브러리가 있습니다.

http://json-lib.sourceforge.net/

여기보면 json-lib라는 놈이 있는데 json으로 손쉽게 변환해주는 라이브러리입니다.

  • jakarta commons-lang 2.3
  • jakarta commons-beanutils 1.7.0
  • jakarta commons-collections 3.2
  • jakarta commons-logging 1.1
  • ezmorph 1.0.4

    이것들이 필요하다더군요. 위에 4개는 apache에 가면 있구요. ezmorph는 구글링해서 찾아서 받으세요.
    그리고 JSON-LIB인 json-lib-2.2.1-jdk15.jar가 필요합니다.

    사용법은 매우 간단합니다.
    [code]
    public class JsonTest {
     
     @Test
     public void Bean2Json()
     {
      MyBean myBean1 = new MyBean();
      myBean1.setId(1);
      myBean1.setName("mudchobo");
      MyBean myBean2 = new MyBean();
      myBean2.setId(2);
      myBean2.setName("shit");
     
      List<MyBean> mybeanList = new ArrayList<MyBean>();
      mybeanList.add(myBean1);
      mybeanList.add(myBean2);
     
      JSONArray jsonArray = JSONArray.fromObject(mybeanList);
      System.out.println("mybeanList - " + jsonArray);
     
      Map<String, Object> map = new HashMap<String, Object>();
      map.put("beanlist", jsonArray);
     
      JSONObject jsonObject = JSONObject.fromObject(map);
      System.out.println("json - " + jsonObject);
     }
    }
    [/code]
    Bean 2개를 List에 add를 한다음에 JSONArray라는 객체가 List를 배열로 만드는놈입니다.

    mybeanList - [{"id":1,"name":"mudchobo"},{"id":2,"name":"shit"}]

    이런식으로 만듭니다.
    저거를 JSONObject클래스를 이용해서 앞에 이름을 붙여줍니다. Map을 이용하면 됩니다
    Map을 이용해서 put에서 첫번째 인자에 이름을 넣고, 두번째 인자에 방금 생성한 Array를 넣으면 됩니다.
    그리고 JSONObject.fromObject메소드를 이용해서 생성하게 되면 이렇게 됩니다.

    json - {"beanlist":[{"id":1,"name":"mudchobo"},{"id":2,"name":"shit"}]}

    이상입니다-_-;

  •  

    반응형
    반응형

    Jakarta POI

    VII. 엑셀 쓰기예제

     

    쓰기도 역시 읽기와 비슷합니다.

    엑셀 워크북을 생성합니다. 행과 셀을 생성하려면 당연한 절차겠죠?

    HSSFWorkbook workbook = new HSSFWorkbook();


     

    시트를 생성합니다.

    시트명을 파라미터로 바로 생성 합니다.

    HSSFSheet sheet = workbook.createSheet("sheet name");


     

    만약 한글로 시트명을 만들려면 다음과 같이 인코딩이 필요합니다.

    HSSFSheet sheet = workbook.createSheet();

    workbook.setSheetName( 0 , "한글" , HSSFWorkbook.ENCODING_UTF_16 );


     

    셀에 사용할 스타일을 미리 생성해 둡니다.

    HSSFCellStyle style = wb.createCellStyle();
    style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
    style.setBottomBorderColor(HSSFColor.BLACK.index);
    style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
    style.setLeftBorderColor(HSSFColor.GREEN.index);
    style.setBorderRight(HSSFCellStyle.BORDER_THIN);
    style.setRightBorderColor(HSSFColor.BLUE.index);
    style.setBorderTop(HSSFCellStyle.BORDER_MEDIUM_DASHED);
    style.setTopBorderColor(HSSFColor.BLACK.index);

    등 여러가지 스타일을 만들 수 있습니다.


     

    스타일은 다음 주소를 참고하세요

    http://jakarta.apache.org/poi/apidocs/org/apache/poi/hssf/usermodel/HSSFCellStyle.html


     

    로우를 하나 생성합니다.

    HSSFRow row = sheet.createRow(0);


     

    셀츨 하나 생성하여 스타일을 주고 값을 입력합니다.

    HSSFCell cell = row.createCell((short)0);

    cell.setCellStyle(style);

    cell.setCellValue("jakarta project!");


     

    만약 한글을 입력한다면 인코딩 해야 하며 값 세팅전에 해야 합니다.

    cell.setEncoding(HSSFCell.ENCODING_UTF_16);  //한글 처리

    cell.setCellStyle(style);

    cell.setCellValue("자카드타 프로젝트!");


     

    모든 셀이 다 입력되었으면 파일을 만듭니다.

    FileOutputStream fs = new FileOutputStream("excelfile.xls");
    workbook.write(fs);
    fs.close();



     

    VIII. 쓰기샘플 소스


    <%@ page language="java" contentType="text/html;charset=euc-kr" %>
    <%@ page import="java.io.*" %>
    <%@ page import="org.apache.poi.poifs.dev.*" %>
    <%@ page import="org.apache.poi.hssf.record.*" %>
    <%@ page import="org.apache.poi.hssf.record.formula.*" %>
    <%@ page import="org.apache.poi.hssf.model.*" %>
    <%@ page import="org.apache.poi.hssf.usermodel.*" %>
    <%@ page import="org.apache.poi.hssf.util.*" %>


    <html>
    <body>

    <%

        String filepath = "C:\\Tomcat 5.0\\webapps\\ROOT\\write.xls";


        try {

            String[] cell_value = {"자카르타","프로젝트","http://www.jakartaproject.com/"};


            HSSFWorkbook workbook = new HSSFWorkbook();


            HSSFSheet sheet = workbook.createSheet();
            workbook.setSheetName(0 , "한글명" ,HSSFWorkbook.ENCODING_UTF_16);


            HSSFCellStyle style = workbook.createCellStyle();
            style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            style.setBottomBorderColor(HSSFColor.BLACK.index);
            style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            style.setLeftBorderColor(HSSFColor.GREEN.index);
            style.setBorderRight(HSSFCellStyle.BORDER_THIN);
            style.setRightBorderColor(HSSFColor.BLUE.index);
            style.setBorderTop(HSSFCellStyle.BORDER_MEDIUM_DASHED);
            style.setTopBorderColor(HSSFColor.BLACK.index);           


            HSSFRow row = sheet.createRow(0);
            for (int i = 0 ; i < cell_value.length; i++){
                HSSFCell cell = row.createCell((short)i);
                cell.setEncoding(HSSFCell.ENCODING_UTF_16);
                cell.setCellStyle(style);
                cell.setCellValue(cell_value[i]);
            }
               
            FileOutputStream fs = null;
            try {
                fs = new FileOutputStream(filepath);
                workbook.write(fs);
            } catch (Exception e) {
            } finally {
                if (fs != null) fs.close();
            }
           
        } catch (Exception e) {
    %>
            Error occurred:  <%= e.getMessage() %>
    <%  
            e.printStackTrace();
        }   
       
    %>

    </body>
    </html>



    자 결과화면 입니다.





     

    성공!


     

    위의 소스를 기본으로 한다면 그리 어렵지 않을겁니다 ^^


     

    참고로 셀병합은


     

    HSSFWorkbook wb = new HSSFWorkbook();
    HSSFSheet sheet = wb.createSheet("new sheet");

    HSSFRow row = sheet.createRow((short) 1);
    HSSFCell cell = row.createCell((short) 1);
    cell.setCellValue("This is a test of merging");

    //셀병합
    //Region(int 시작row, short 시작col, int 종료row, short 종료col)
    sheet.addMergedRegion(new Region(1,(short)1,1,(short)2));

    FileOutputStream fileOut = new FileOutputStream("workbook.xls");
    wb.write(fileOut);
    fileOut.close();

    와 같이하면 됩니다

    반응형
    반응형

    import sun.misc.BASE64Decoder;
    import sun.misc.BASE64Encoder;

     

    를 사용하려고 하는데 다음과 같은 메시지가 이클립스 화면에 보였다.

     

    Access restriction: The type BASE64Encoder is not accessible due to restriction on required library.

    Access restriction: The type BASE64Decoder is not accessible due to restriction on required library.

     

    이 문제는 네이버의 검색을 통해 다음과 같이 해결하였다.

     

    이클립스 환경설정을 열어 아래와 같이 설정한다.

    Windows - Preferences

     

     

     

    Apply 를 누르고 OK를 누르면

    코드상의 에러표시부분이 경고표시로 바뀌었음을 확인할 수 있다.

     

    반응형
    반응형

    올해는 모든것이 새롭다.

    회사도, 개인삶도, 삶의 터전도... 

    내 삶의 흔적들을 보다 아름답고 즐거운 맘으로 사랑하고자 스토리를 만든다.

    just Enjoy~~^^

    반응형

    + Recent posts