JAVA/Core Java

[jxl] 존재하는 Excel File 에 새로운 엑셀 데이터 추가...

tornado 2007. 3. 14. 15:24

오랜만에 자바 코딩해봤음 ^^

jxl 예제에 엑셀 파일 생성, 읽기 부분만 나와있고 기존 파일에 추가하는 방법이 안나와서,
API 를 보니


public static WritableWorkbook createWorkbook(java.io.File file,
                                              Workbook in)
                                       throws java.io.IOException
Creates a writable workbook with the given filename as a copy of the workbook passed in. Once created, the contents of the writable workbook may be modified
Parameters:
file - the output file for the copy
in - the workbook to copy
Returns:
a writable workbook
Throws:
java.io.IOException



요런 부분이 있음.

글치.. 왜 없었겠어~ 그래서 API 를 자세히 봐야지~

아래는 간단하게 테스트 해본 소스이다.

1번줄 부터 생성한 이유는 엑셀 파일 첫줄이 Select box 로 정렬 할 수 있게 해놨기 때문임.



----------------------------------------------------------------------------------
package com.javarush;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

public class JxlUtil {
 
 public static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
 
 public File getExcelToOrder() throws Exception{
 
  File dir = new File("d:/springStudy/JxlTest/src/com/javarush/");
  File f = new File(dir, "excel_default.xls");
 
  if(!f.exists()){
   throw new Exception("file not found");
  }
 
  if(!f.canRead()){
   throw new Exception("can't read file");
  }

  Workbook workbook = Workbook.getWorkbook(f);
 
  if(workbook == null){
   throw new Exception("Workbook is null!!");
  }
 
  File newExcel = new File(dir, System.currentTimeMillis() + ".xls");
     
  WritableWorkbook writeBook = Workbook.createWorkbook(newExcel, workbook);

  WritableSheet writeSheet = writeBook.getSheet(0);
 
  // 1열의 0번행에 ^^ 를 출력
  Label a = new Label(0,1, "^^");
 
  // 1열의 1번행에 날짜 출력
  Label d = new Label(1, 1, sdf.format( Calendar.getInstance().getTime()));
   
  writeSheet.addCell(a);
  writeSheet.addCell(d);
 
  writeBook.write();
  writeBook.close();
 
  return newExcel;
 }
}