본문 바로가기

IT/Spring

Spring에서 excel 사용하기 JXL & POI 개념 및 예제

자바로 엑셀을 핸들링 있는 방법은 크게 두가지로 나누어 진다. 

 

1. Java Excel API     

    참조 :http://jexcelapi.sourceforge.net/ 

2. POI 

 

 

 

    흔히 POI 엑셀을 핸들링 하기 위한 것으로만 오해하기 쉬운데, 

    POI 프로젝트는 마이크로소프트 OLE 2 복합도큐먼트포맷형식의 파일을 순수 자바를 이용하여 핸들링하는 APIs 구성되어있다. 

    OLE 2 복합도큐먼트포맷형식의 파일은 마이크로소프트 엑셀 혹은 워드파일 등의 대부분의 오피스파일들을 나타낸다. 

 

 

 

일반적으로 엑셀에 대한 핸들링만을 수행할 때에는 Jxl 권장한다. 

엑셀을 핸들링 엑셀에서 가장 작은 단위는 알고 있듯이 ""이다. 

모든 작업은 셀을 중심으로 이루어진다. 

 

 

 

주의할 ) 

1) 엑셀 쉬트상에 "C15"라는 셀에 데이터가 있다고 가정하자.( 15 C열을 나타낸다.) 

Jxl에서는  A1( 1 A)부터  C15까지는 실제 데이터가 없을 경우에라도 null 아닌 빈데이터가 있다고 인식한다. 

D 이상이나, 16 이상을 접근 때에 null 인식한다. 

 

하지만 POI에서는 C15 이내에 있다 하더라도 실제 데이터가 없을 때에는 null 인식한다. 

 

2) Jxl에서는 셀의 데이터 타입을 실제 엑셀 파일에서 지정된 셀의 타입을 따르고, 

   POI에서는 셀의 실제 데이터 형을 따른다. 

   예를 들어 특정 셀의 타입을 text 잡아놓고, 데이터를 1234 입력하면 

   Jxl에서는 "12345" 인식하고, POI에서는 12345.00 이런식으로 인식한다. 

 

 

 

EX ) Java Excel API 이용한 Excel 읽기 

 

import jxl.*; 

 

// .. 중간생략 

 

    Workbook workbook = null; 

    Sheet sheet = null; 

    Cell cell = null; 

 

    try 

    { 

        //엑셀파일을 인식 

        workbook = Workbook.getWorkbook( new File( szFileName)); 

 

        //엑셀파일에 포함된 sheet 배열을 리턴한다. 

        //workbook.getSheets(); 

 

        if( workbook != null) 

        { 

            //엑셀파일에서 첫번째 Sheet 인식 

            sheet = workbook.getSheet(0); 

 

            if( sheet != null) 

            { 

                //셀인식 Cell a1 = sheet.getCell( 컬럼 Index, Index); 

                // 내용 String stringa1 = a1.getContents(); 

 

                //기록물철의 경우 실제 데이터가 시작되는 Row지정 

                int nRowStartIndex = 5; 

                //기록물철의 경우 실제 데이터가 Row지정 

                int nRowEndIndex   = sheet.getColumn( 2).length - 1; 

 

                //기록물철의 경우 실제 데이터가 시작되는 Column지정 

                int nColumnStartIndex = 2; 

                //기록물철의 경우 실제 데이터가 끝나는 Column지정 

                int nColumnEndIndex = sheet.getRow( 2).length - 1; 

 

                String szValue = ""; 

 

                for( int nRow = nRowStartIndex; nRow <= nRowEndIndex; nRow++ ) 

                { 

                    for( int nColumn = nColumnStartIndex; nColumn <= nColumnEndIndex ; nColumn++) 

                    { 

                        szValue = sheet.getCell( nColumn, nRow).getContents(); 

 

                        System.out.print( szValue); 

                        System.out.print( "\t" ); 

                    } 

                    System.out.println(); 

                } 

            } 

            else 

            { 

                System.out.println( "Sheet is null!!" ); 

            } 

        } 

        else 

        { 

            System.out.println( "WorkBook is null!!" ); 

        } 

    } 

    catch( Exception e) 

    { 

        e.printStackTrace(); 

    } 

    finally 

    { 

        if( workbook != null) 

        { 

            workbook.close(); 

        } 

    } 

 

EX ) POI 이용한 Excel 파일 읽기 

 

import org.apache.poi.hssf.usermodel.*; 

 

// .. 중간 생략 

 

    HSSFWorkbook workbook = null; 

    HSSFSheet sheet = null; 

    HSSFRow row = null; 

    HSSFCell cell = null; 

 

    try 

    { 

        workbook = new HSSFWorkbook( new FileInputStream( new File( szFileName))); 

 

        if( workbook != null) 

        { 

            sheet = workbook.getSheetAt( 0); 

 

            if( sheet != null) 

            { 

 

                //기록물철의 경우 실제 데이터가 시작되는 Row지정 

                int nRowStartIndex = 5; 

                //기록물철의 경우 실제 데이터가 Row지정 

                int nRowEndIndex   = sheet.getLastRowNum(); 

 

                //기록물철의 경우 실제 데이터가 시작되는 Column지정 

                int nColumnStartIndex = 2; 

                //기록물철의 경우 실제 데이터가 끝나는 Column지정 

                int nColumnEndIndex = sheet.getRow( 2).getLastCellNum(); 

 

                String szValue = ""; 

 

                for( int i = nRowStartIndex; i <= nRowEndIndex ; i++) 

                { 

                    row  = sheet.getRow( i); 

 

                    for( int nColumn = nColumnStartIndex; nColumn <= nColumnEndIndex ; nColumn++) 

                    { 

                        cell = row.getCell(( short ) nColumn); 

                         

                        if( cell == null) 

                        { 

                            continue; 

                        } 

                        if( cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) 

                        { 

                            szValue = String.valueOf( cell.getNumericCellValue()); 

                        } 

                        else 

                        { 

                            szValue = cell.getStringCellValue(); 

                        } 

 

                        System.out.print( szValue); 

                        System.out.print( "\t" ); 

                    } 

                    System.out.println(); 

                } 

            } 

            else 

            { 

                System.out.println( "Sheet is null!!" ); 

            } 

        } 

        else 

        { 

            System.out.println( "WorkBook is null!!" ); 

        } 

 

    }catch(Exception e){ 

        e.printStackTrace(); 

    } 

 

 

EX ) Jxl 이용하여 Excel 데이터 저장하기 

 

import jxl.*; 

 

// .. 중간생략 

 

    WritableWorkbook workbook = null; 

WritableSheet sheet = null; 

 

File excelFile = new File( szFileName); 

Label label = null; 

 

long start = 0; 

   long end = 0; 

   

    try 

    { 

        for(int i = 0 ; i < 10; i++) 

        { 

            workbook = Workbook.createWorkbook( excelFile); 

            workbook.createSheet("sheet1", 0); 

            sheet = workbook.getSheet(0); 

            for( int j = 0; j < 10000; j++){ 

                label = new Label( j, 0, "test cell"); 

                sheet.addCell( label); 

            } 

 

            kidsbook.write(); 

            kidsbook.close(); 

        } 

    } 

    catch( Exception e) 

    { 

    } 

 

// .. 중간생략 

 

 

EX ) POI 이용한 브라우저에서 Excel 데이터 저장하여 보여주기 

 

import org.apache.poi.hssf.usermodel.*; 

 

// ... 생략 

 

public void writeStream( PTSEvaluation[] arrPTSEvaluation) throws Exception 

{ 

    try 

    { 

 

        HSSFWorkbook wb = new HSSFWorkbook(); 

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

        HSSFRow row = null; 

        HSSFCell cell = null; 

        HSSFCellStyle style = null; 

 

        ServletOutputStream excelOut = ServiceContext.getResponse().getOutputStream(); 

        ServiceContext.getResponse().setHeader( "Content-Disposition", "attachment;filename=EvaluationCompensationList.xls"); 

        ServiceContext.getResponse().setContentType( MimeType.getMimeType( "xls")); 

 

        //로우 생성 

        row = sheet.createRow( ( short)0); 

        row.setHeightInPoints( 30); 

 

        //셀에 적용한 스타일을 생성한다. 

        style = PTSUtil.setExcelHeaderStyle( wb); 

 

        // 생성 

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

 

        //한글 처리 

        cell.setEncoding( HSSFCell.ENCODING_UTF_16);   

 

        //셀에 데이터 입력하기 

        cell.setCellValue( ""); 

 

        //셀에 스타일 적용하기 

        cell.setCellStyle(style); 

 

        //.. 중간생략 ( 이런 방식으로 로우와 셀을 증가 시키면서 작업을 수행하면 된다. 

 

        wb.write( excelOut); 

        excelOut.flush(); 

    } 

    catch( Exception e) 

    { 

        e.printStackTrace(); 

        throw e; 

    } 

    finally 

    { 

        ServiceContext.getResponse().getOutputStream().close(); 

    } 

} 

'IT > Spring' 카테고리의 다른 글

Spring Annotation 설명 및 예제  (0) 2015.01.31
Spring MVC 예제  (0) 2015.01.30
Spring JDBC framework 개념 및 예제  (0) 2015.01.22
Spring-IOC (DI) 개념 및 예제  (2) 2015.01.21
Spring 이론  (0) 2015.01.20