import java.io.File;
import java.io.FileInputStream;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFCell;

/**
 * Excel Read 한다. xls, xlsx 가능
 * ex) 	ExcelGenerator.excelToList(new File("path..xls,xlsx");
 * 		ExcelGenerator.excelToList(new File("path..xls,xlsx", new Integer[]{x, y, width, height});
 * ExcelGenerator.excelToList(new File("path..xls,xlsx", x, y, width, height);
 * 		java.awt.Rectangle(int x, int y, int width, int height) 와 같은 형태로 왼쪽 위 모서리 좌표와, 오른쪽 아래 모서리 좌표 정보 
 * @author 	ddakker
 * @version 1.0
 * @date	2012.05.04
 *
 */
public class ExcelGenerator {
	private static final Log logger = LogFactory.getLog(ExcelGenerator.class);
	
	public static Object[][] excelToList(File file ) throws Exception {
		return excelToList(file, 0, null);
	}
	
	/**
	 * 엑셀 데이터를 Object[colunm][row] 형태로 변환한다.
	 * @param file			엑셀 파일(xls, xlsx)
	 * @param x				왼쪽 위 모서리 x
	 * @param y				왼쪽 위 모서리 y
	 * @param width			오른쪽 아래 모서리 x
	 * @param height		오른쪽 아래 모서리 y
	 * @return
	 * @throws Exception
	 */
	public static Object[][] excelToList(File file, int x, int y, int width, int height) throws Exception {
		Integer [] colRow = {x, y, width, height};
		return excelToList(file, 0, colRow);
	}
	
	/**
	 * 엑셀 데이터를 Object[colunm][row] 형태로 변환한다.
	 * @param file			엑셀 파일(xls, xlsx)
	 * @param colRow		범위 지정 new Integer[]{왼쪽 위 모서리 x, 왼쪽 위 모서리 y, 오른쪽 아래 모서리 x, 오른쪽 아래 모서리 y}
	 * @return
	 * @throws Exception
	 */
	public static Object[][] excelToList(File file, Integer [] colRow) throws Exception {
		return excelToList(file, 0, colRow);
	}
	
	/**
	 * 엑셀 데이터를 Object[colunm][row] 형태로 변환한다.
	 * @param file			엑셀 파일(xls, xlsx)
	 * @param sheetIndex	시트 번호
	 * @return
	 * @throws Exception
	 */
	public static Object[][] excelToList(File file, int sheetIndex) throws Exception {
		return excelToList(file, sheetIndex, null);
	}
	
	/**
	 * 엑셀 데이터를 Object[colunm][row] 형태로 변환한다.
	 * @param file				엑셀 파일(xls, xlsx)
	 * @param sheetIndex		시트 번호
	 * @param colRow			범위 지정 new Integer[]{왼쪽 위 모서리 x, 왼쪽 위 모서리 y, 오른쪽 아래 모서리 x, 오른쪽 아래 모서리 y}
	 * @return
	 */
	public static Object[][] excelToList(File file, int sheetIndex, Integer [] colRow) throws Exception {
		Object [][] contentData = null;
		
		FileInputStream fis			= null;
		Workbook 		workBook	= null;
        Sheet			sheet		= null;
        
        try {
        	if( colRow != null ){
	        	if( colRow.length != 4 )					throw new Exception("colRow[] 무조껀 셋팅 해야 합니다. ex) new Integer[]{0,0,6,2}");
	        	if( !(colRow[0] >= 0 && colRow[1] >= 0) )	throw new Exception("colRow[] 0 이상 입력 하시요. ex) new Integer[]{1,1,6,2}");
	        	if( !(colRow[2] >= 0 && colRow[3] >= 0) )	throw new Exception("colRow[] 0 이상 입력 하시요. ex) new Integer[]{1,1,6,2}");
        	}
        	fis			= new FileInputStream(file);
        	workBook	= WorkbookFactory.create(fis);
    		sheet		= workBook.getSheetAt(sheetIndex);
            
            int minCol = colRow==null?0:colRow[0];
            int maxCol = colRow==null?-1:colRow[2]+1;
            
            int minRow = colRow==null?0:colRow[1];
            int maxRow = colRow==null?sheet.getPhysicalNumberOfRows():colRow[3]+1;
            
            FormulaEvaluator evaluator = workBook.getCreationHelper().createFormulaEvaluator();
            
            for( int i=minRow; i<maxRow; i++ ) {
            	Row row = sheet.getRow(i);
            	if( i-minRow == 0 ){
	            	if( maxCol == -1 ){
	            		maxCol = row.getPhysicalNumberOfCells();
	            	}
	            	contentData = new Object[maxRow-minRow][maxCol-minCol];
            	}
                for( int j=minCol; j<maxCol; j++ ) {
                	Cell cell = row.getCell(j)==null?row.createCell(j):row.getCell(j);
                	
                	Object value = null;
                    switch( cell.getCellType() ) {
                         case XSSFCell.CELL_TYPE_FORMULA :
                        	 if( !(cell.toString() == "") ){
	                             if(evaluator.evaluateFormulaCell(cell)==XSSFCell.CELL_TYPE_NUMERIC){
	                            	 //value = cell.getNumericCellValue();         
	                            	 value = String.valueOf(new Double(cell.getNumericCellValue()).intValue());
	                             }else if(evaluator.evaluateFormulaCell(cell)==XSSFCell.CELL_TYPE_STRING){
	                            	 value = cell.getStringCellValue();
	                             }else if(evaluator.evaluateFormulaCell(cell)==XSSFCell.CELL_TYPE_BOOLEAN){
	                                  value = String.valueOf(cell.getBooleanCellValue());         
	                             }
                        	 }
                        	 break;
                         case XSSFCell.CELL_TYPE_NUMERIC :
                        	 //value = cell.getNumericCellValue();
                        	 value = String.valueOf(new Double(cell.getNumericCellValue()).intValue());
                             break;
                         case XSSFCell.CELL_TYPE_STRING :
                        	 value = cell.getStringCellValue()==null?new String(""):cell.getStringCellValue();
                        	 break;
                         case XSSFCell.CELL_TYPE_BOOLEAN :
                        	 value = Boolean.toString(cell.getBooleanCellValue()); //boolean
                        	 break;
                         default :
                    }
                    
                    logger.debug("xlsx ["+i+"]["+j+"]=" + ((cell==null || value==null)?"":value));
                    contentData[i-minRow][j-minCol] = (value==null)?new String(""):value;
                }
            }
        } catch (Exception e) {
        	logger.error(e);
            throw new Exception("POI Excel Read 중 오류가 발생하였습니다.");
        } finally {
        	if( fis != null ) fis.close();
        }
        return contentData;
    }

    /**
	 * List 데이터를 엑셀 형식으로 변환한다.
	 * 		* String만 테스트 해봄.. 다른 데이터형은 직접 테스트 해보실것!!![2013.08.22]
	 * @param list
	 * @return
	 * @throws Exception
	 * @auther ddakker 2013. 8. 22.
	 */
	public static HSSFWorkbook listToExcel(List> list) throws Exception {
		HSSFWorkbook wb = null;
		try{

			wb = new HSSFWorkbook();
			HSSFRow row = null;
			HSSFCell cell = null;

			HSSFSheet sheet = wb.createSheet();

			wb.setSheetName(0, "Sheet1");
			sheet.setColumnWidth(0, sheet.getDefaultColumnWidth() * 700);
			sheet.setColumnWidth(1, sheet.getDefaultColumnWidth() * 4300);

			HSSFCellStyle titleCellStyle = wb.createCellStyle();
			titleCellStyle.setBorderBottom(HSSFCellStyle.BORDER_THICK);
			titleCellStyle.setBorderLeft(HSSFCellStyle.BORDER_THICK);
			titleCellStyle.setBorderRight(HSSFCellStyle.BORDER_THICK);
			titleCellStyle.setBorderTop(HSSFCellStyle.BORDER_THICK);
			titleCellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
			titleCellStyle.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);

			Iterator it = list.get(0).keySet().iterator();
			int haderIdx = 0;
			HSSFRow titleRow = sheet.createRow(0);
			while (it.hasNext()) {
				String key = it.next();

				cell = titleRow.createCell(haderIdx++);
				cell.setCellValue(key);
				cell.setCellStyle(titleCellStyle);
			}

			HSSFCellStyle contentCellStyle = wb.createCellStyle();
			contentCellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
			contentCellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
			contentCellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
			contentCellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
			contentCellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
			contentCellStyle.setFillForegroundColor(HSSFColor.WHITE.index);

			for( int i=0,size=list.size(); i<size; i++ ){
				row = sheet.createRow((i+1));

				it = list.get(0).keySet().iterator();
				haderIdx = 0;
				while (it.hasNext()) {
					String key = it.next();

					cell = row.createCell(haderIdx++);
					cell.setCellStyle(contentCellStyle);

					if( list.get(i).get(key) instanceof String ) 			cell.setCellValue( (String) list.get(i).get(key) );
					if( list.get(i).get(key) instanceof Integer ) 			cell.setCellValue( (Integer) list.get(i).get(key) );
					if( list.get(i).get(key) instanceof Long ) 				cell.setCellValue( (Long) list.get(i).get(key) );
					if( list.get(i).get(key) instanceof Float ) 			cell.setCellValue( (Float) list.get(i).get(key) );
					if( list.get(i).get(key) instanceof Double ) 			cell.setCellValue( (Double) list.get(i).get(key) );
					if( list.get(i).get(key) instanceof Date ) 				cell.setCellValue( (Date) list.get(i).get(key) );
					if( list.get(i).get(key) instanceof java.sql.Date ) 	cell.setCellValue( (java.sql.Date) list.get(i).get(key) );
				}
			}
		}catch(Exception e){
			logger.error("POI List에서 Excel로 변환 중 오류가 발생하였습니다.");
			logger.error(e);
		}
		return wb;
	}
}

--------------


dom4j-1.6.1.jar

poi-3.6-20091214.jar

poi-ooxml-3.6-20091214.jar

poi-ooxml-schemas-3.6-20091214.jar

xmlbeans-2.3.0.jar

+ Recent posts