2009년 3월 5일 목요일

beanutils를 이용한 excel import

excel파일을 받아서 특정 bean array로 만들어 처리해야 하는 경우...

 

1. excel를 읽어오는 library가 필요 : 아래 2개를 찾아 냄

 - apache의 poi 

 - Java Excel API

 

2. 읽어온 data를 특정 객체에 넣기

 - apache commons의 beanutils를 이용함

 

[먼저]

I. apache POI는 MS Office에서 제공하는 가능한 모든 포멧을 java에서 읽거나 쓰기 위해 만든 프로젝트이다. 그중 HSSF+XSSF는 엑셀에 관해 처리하는 부분이며 이게 관한 api를 제공하고 있다.

참고로 HSSF는 97~2003까지 xls 확장자를 다루며, XSSF는 2007버젼의 xlsx 확장자를 다룬다.

POI는 office 전반을 controll하기 때문에 무겁고 광대하며 자세하다.

II. java excel api는 sourceforge에 등록된 excel controll을 목적으로 한 오픈소스 프로젝트로, 가볍고 간단하다는 장점이 있다. (과거 유명한 jxl프로젝트와 무슨 관계인지 jxl.jar로 배포하고 있다)

 

[내용]

POI와 JXL을 선택적으로 사용해야 할 수도 있기에, interface를 제공하고 factory로 처리하고 했다.

 

=== Interface ===

public interface Importer {
 
 public void process() throws Exception ;

 public Object getResult();
}

 

=== POIInporter ===

import  org.apache.poi.hssf.usermodel.*;
import  org.apache.poi.hssf.model.Workbook;
import  org.apache.poi.hssf.model.Sheet;
import  org.apache.poi.hssf.*;
import  org.apache.poi.hssf.util.*;
import  org.apache.poi.poifs.filesystem.*;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.List;
import java.util.ArrayList;


public class ExcelImporter implements Importer {

 POIFSFileSystem fs = null;
 FileOutputStream fileOut = null;

 String fileName  = "";
 int processCount = 0;
 
 HSSFWorkbook wb = null;
 HSSFSheet sheet = null;

 List resultObj = null;
 

 public ExcelImporter(String fn) {
  this.fileName = fn;
 }
 
 public void process() throws Exception {
  FileInputStream fi = new FileInputStream(fileName);
  try{

   fs  = new POIFSFileSystem(fi);
   //if(fs  != null) System.out.println("file name_______ =>"+fileName);
   //if(fs  != null) System.out.println("fs _______ =>"+fs);


   wb = new HSSFWorkbook(fs);
   System.out.println("WB =>"+wb);
   
   sheet = wb.getSheetAt(0);
   int totalRowNum = sheet.getPhysicalNumberOfRows();
   //int  totalRowNum = sheet.getLastRowNum();
   int rowIndex= 0;

   
   HSSFRow row = null;
   short cellSize = 0;
   HSSFCell[] cells = null ;
   HSSFCell cell = null ;
   

   resultObj = new ArrayList();
   
   //System.out.println("*** totalRowNum=>"+totalRowNum);
   
   Object[] obj = null;
   for(int k=0; k<totalRowNum; k++) {
    row = sheet.getRow(k);            
    if(row == null) continue;
    if(k==0) cellSize = row.getLastCellNum();
   
    obj = new Object[cellSize];
    //System.out.println("*** cellSize=>"+cellSize);
    cells = new HSSFCell[cellSize];  
    for(int i=0; i<cellSize; i++) {
     cells[i] = row.getCell(i);
     obj[i] = new Object();
     //System.out.println("cells[i].getStringCellValue()=>"+cells[i].getStringCellValue());    
     obj[i] = cells[i].getStringCellValue();
    }
    resultObj.add(obj);
   }

  }catch(Exception ex) {
   throw ex;
  }finally{
   if(fi != null) try{ fi.close(); } catch(Exception ex2) { }
  }
 
 }

 public Object getResult() {
  return resultObj;
 }

 

}

 

 

=== JXLInporter ===

 

import jxl.*;
import java.io.File;
import java.util.List;
import java.util.ArrayList;

public class JExcelImporter implements Importer {

 String fileName = "";
 int processCount = 0;

 Workbook workbook = null;
 Sheet sheet = null;
 List resultObj = null;
 
 public JExcelImporter(String fn) {
  this.fileName = fn;
 }
 
 public void process() throws Exception {
 
  try{  
   workbook = Workbook.getWorkbook(new File(fileName));

   sheet = workbook.getSheet(0);
   
   int totalRowNum = sheet.getRows();
   int cellSize = sheet.getColumns();
 
   //System.out.println("***************************** totalRowNum=>"+totalRowNum);    
   //System.out.println("***************************** cellSize=>"+cellSize);    
   
   int rowIndex= 0;
   
   Cell[] cells = null ;
   Cell cell = null ;
   
   resultObj = new ArrayList();
     
   Object[] obj = null;
   for(int k=0; k<totalRowNum; k++) {
    cells = sheet.getRow(k);

    if(cells  == null ) continue;
   
   
    obj = new Object[cellSize];
   
    for(int i=0; i<cellSize; i++) {    
     obj[i] = new Object();    
     obj[i] = cells[i].getContents();
    }
    resultObj.add(obj);
   }

  }catch(Exception ex) {
   throw ex;
  }finally{
   if(workbook != null) try{ workbook.close(); } catch(Exception ex2) { }
  }
 
 }

 public Object getResult() {
  return resultObj;
 }

}

 

=== Excel Util ===

 

/**
 * 엑셀(xls)파일을 읽어서 Bean Array에 넣는 Util
 * @FileName  : ExcelUtil.java
 * @Project   : nurien
 * @Date      : 2009. 03. 01
 * @Auther    : sunjin.kim
 * @History   :
 * @Comment   :
 *  Caption : xlsx(office 2007)파일 지원 안함. 저장시 97~2003통합문서로 저장.
 *  Usage : 1. xls 최상단에 컬럼명을 넣는다
 *    2. new ExcelUtil(파일경로, 클래스명, data가 시작되는 row)
 *    3. 클래스명 : package를 포함한 class명
 */

import org.apache.commons.beanutils.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

import com.nurien.base.util.importer.*;

public class ExcelUtil {
 private String fileName;
 private String beanClassName;
 private int dataRow;
 
 public ExcelUtil(String fn, String bc, int dr){
  this.fileName = fn;
  this.beanClassName = bc;
  this.dataRow = dr;
 }
 
 public List getImportObject(){
  Importer importer = ImporterFactory.getInstance(fileName, ImporterFactory.JEXCEL);
  List list = null;
  try{
   importer.process();
   list = (List)importer.getResult();
  }catch(Exception ex) {
   ex.printStackTrace();
  }
  return list;
 }
 
 public String[] getHeaderInfo(List list) {
  Object[] obj = (Object[])list.get(0);
  String hs[] = null;
  if(obj != null) {
   hs = new String[obj.length];
   for(int i=0; i<obj.length; i++) {
    hs[i] = (String)obj[i];
    hs[i] = hs[i].toLowerCase().trim();
   }
  }
  return hs;
 }
 
 public List getImportData() {

  List importObj = getImportObject();
  if(importObj == null) return null;
 
  String[] heads = null;

  heads = getHeaderInfo(importObj);
  if(heads == null) return null;
 
  List list = new ArrayList();
  Map map = new HashMap();
 
  try{  
   heads = getHeaderInfo(importObj);
   for(int k=dataRow; k<importObj.size(); k++) { //dataRow번째 행부터 data로 인식

    Object[] objImportValues = (Object[])importObj.get(k);
    Object obj = Class.forName(beanClassName).newInstance();
    for(int i=0; i<heads.length; i++) {
     Object typeObj = PropertyUtils.getProperty(obj,heads[i]);
     if(typeObj.getClass().getName().equals("java.lang.String")) {
      map.put(heads[i],(String)objImportValues[i]);      
     }else {
      map.put(heads[i],new Integer((String)objImportValues[i]));
     }
    }
    PropertyUtils.copyProperties(obj,map);
    list.add(obj);
    map.clear();
   }

  }catch(Exception ex) {
   ex.printStackTrace(System.err);
   return null;
  }

  return list;
 }
 
 public static void main(String[] args){
  /*
  if(args.length < 2){
   System.out.println("Please insert Excel File Name and Data Row Number");
   System.exit(0);
  }
  String fileName = args[0];
  int dataRow = Integer.parseInt(args[1]);
  String className = "com.textcube.babyp.product";
  ExcelUtil eu = new ExcelUtil(fileName,className,dataRow);
  List list = eu.getImportData();
  com.nurien.bbs.entity.Product[] plist = null;
  if(list != null){
   System.out.println("data length : "+list.size());
   plist = new com.nurien.bbs.entity.Product[list.size()];
   for(int i=0; i<list.size(); i++){
    plist = (com.nurien.bbs.entity.Product[])list.toArray(plist);
   }
   
   for(int i=0; i<plist.length; i++){
    //System.out.println(plist[i].toString());
   }
  }
  */
 }
 
}

 

0 개의 댓글:

댓글 쓰기