달력

3

« 2024/3 »

  • 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
2011. 7. 4. 13:26

JAVA에서 엑셀 파일 읽고 쓰기 I.lib()/I.lib(Java)2011. 7. 4. 13:26

.. .. ..
 우선 http://www.andykhan.com/jexcelapi/download.html 에 가서 jexcelapi_2_4_5.tar.gz 파일을 다운로드해서 압출을 해제한다.
압축 파일안에 보면 jxl.jar 파일이 있다. java classpath에 이 파일을 걸어준다.
아래 링크는 Tutorial이 나와있는 사이트이다.



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

1. Java Excel API
http://www.andykhan.com/jexcelapi/
2. POI
http://jakarta.apache.org/poi/index.html

※ 흔히 POI를 엑셀을 핸들링 하기 위한 것으로만 오해하기 쉬운데, POI 프로젝트는 마이크로소프트 OLE 2 복합 도큐먼트 포맷의 파일을 순수 자바를 이용하여 핸들링하는 APIs로 구성되어 있다. OLE 2 복합 도큐먼트 포맷의 파일은 Microsoft 엑셀 혹은 워드 파일 등의 대부분의 오피스 파일들을 나타낸다.

일반적으로 엑셀에 대한 핸들링만을 수행할 때에는 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) 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.*;

// .. 중간 생략

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) 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();
}
}


-----------------------------------------------------------------------------------
HSSF를 이용해 자바에서 간단한 엑셀 파일을 생성하는 방법을 살펴보도록 하겠다. HSSF를 사용하기 위해서는 먼저 POI 라이브러리를 다운받아야 하는데 아래의 주소에 가서 라이브러리를 다운받은 후 클래스 패스를 잡아주면 된다.


아래의 소스는 간단한 엑셀파일 생성에 관한 소스이다.
import java.io.*;
import org.apache.poi.hssf.usermodel.*;

public class NumberForm {
public static void main(String[] args) throws IOException, InterruptedException {
// 먼저 파일이 되는 workbook부분을 생성한다.
HSSFWorkbook workbook = new HSSFWorkbook();

// workbook부분에 sheet를 새로 생성한다.
HSSFSheet sheet = workbook.createSheet("new");

// sheet부분에 행을 새로 생성한다.
HSSFRow row = sheet.createRow((short)0);

// 새로 생성된 행 부분에 셀을 추가한다.
HSSFCell cell = row.createCell((short)0);

// 셀 값을 집어넣는다(숫자형)
cell.setCellValue(1);

// 셀 값을 집어넣는다(실수형)
row.createCell((short)1).setCellValue(1.2);
// 셀 값을 집어넣는다(문자형)
row.createCell((short)2).setCellValue("string");
// 셀 값을 집어넣는다(boolean형)
row.createCell((short)3).setCellValue(true);

FileOutputStream outFile = new FileOutputStream("newexcelfile.xls");
workbook.write(outFile);
outFile.close();
}
}


새로이 Excel파일을 만드는 방법은 기본적으로 다음과 같다.

1. WorkBook를 만든다 (즉, 파일이 될 부분을 만든다)
2. WorkBook안에 sheet를 만든다
3. sheet안에 행을 만든다
4. 행 안에 기본단위인 셀을 만든다

* 이때 하늘색 바탕으로 표시된 부분이 인텍스 값이 되며, 인덱스는 0부터 시작한다.

[펌] http://jetzt.tistory.com/18

'I.lib() > I.lib(Java)' 카테고리의 다른 글

JAVA 로 MAIL 보내기.(SMTP 방식?! )  (2) 2011.09.26
필터 스트림  (1) 2011.08.02
Spy 설정 방법.  (1) 2011.03.31
SPY 설정 방법. ( tomcat + axis2 + ibatis )  (0) 2010.10.28
JNI (JAVA Native Interface ) 란? & 사용법.  (0) 2010.07.27
.
:
Posted by .07274.