자바 반사 처리 excel 데이터 가져오기 예시

public class ExcelImportUtils{

	private static final Logger log = Logger.getLogger(ExcelImportUtils.class);

	public static <T> Object handlerExcel(String pathname,String classpath,
			int row,int cloNum) throws ClassNotFoundException,
			InstantiationException,IllegalAccessException{
		Class model = Class.forName(classpath);
		T mobject = (T)model.newInstance();
		try{
			Workbook book = Workbook.getWorkbook(new File(Global.UPLOAD_FOLDER
					+ File.separator + pathname));
			Sheet sheet = book.getSheet(0);
			int rows = sheet.getRows();
			for (int j = row;j < rows;j++){
				// Cell[] cell = sheet.getRow(j);
				// for (int i = 0;i < cell.length;j++){
				// getCell( , )
				/**
				 * @author wzx  java , ,setter/getter   
				 */
				Field[] field = model.getDeclaredFields(); //  , Field 
				// Method[] method=model.getDeclaredMethods();
				try{
					String name = field[j - row].getName(); //  
					name = name.substring(0,1).toUpperCase()
							+ name.substring(1);
					String type = field[j - row].getGenericType().toString(); //  
					if (type.equals("class java.lang.Integer")){
						Method m = model.getMethod("set" + name,Integer.class);
						m.invoke(mobject,Integer.valueOf(sheet
								.getCell(cloNum,j).getContents()));
					}
					if (type.equals("class java.lang.Double")){
						Method m = model.getMethod("set" + name,Double.class);
						m.invoke(mobject,Double.valueOf(sheet.getCell(cloNum,j)
								.getContents()));
					}
					if (type.equals("class java.lang.String")){
						Method m = model.getMethod("set" + name,String.class);
						m.invoke(mobject,sheet.getCell(cloNum,j).getContents());
					}
				}
				catch (NoSuchMethodException e){
					e.printStackTrace();
				}
				catch (SecurityException e){
					e.printStackTrace();
				}
				catch (IllegalAccessException e){
					e.printStackTrace();
				}
				catch (IllegalArgumentException e){
					e.printStackTrace();
				}
				catch (InvocationTargetException e){
					e.printStackTrace();
				}
			}
			// }
			//  
			book.close();
		}
		catch (BiffException e){
			log.info(" *****************");
			log.error(e.getMessage(),e);
			e.printStackTrace();
		}
		catch (IOException e){
			log.error(e.getMessage(),e);
			e.printStackTrace();
		}
		return mobject;
	}

}

좋은 웹페이지 즐겨찾기