InputExcel.java
package com.gxuwz.Market.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import jxl.Sheet;
import jxl.Workbook;
public class InputExcel<T> {
public List<T> realExcel(File file,Class<?> clazz){
List<T> list = new ArrayList<T>();
try{
InputStream is = new FileInputStream(file.getAbsolutePath());
Workbook wb = Workbook.getWorkbook(is);
//Excel的页签数量
Sheet sheet = wb.getSheet(0);
for(int i = 1;i < sheet.getRows();i++){
Object o = clazz.newInstance();
for(int j = 0;j < sheet.getColumns();j++){
String cellInfo = sheet.getCell(j,i).getContents();
setMethod(o, formatMethodName(sheet.getCell(j,0).getContents()), cellInfo);
}
list.add((T) o);
}
}catch(Exception e){
e.printStackTrace();
}
return list;
}
/**
* 通过
* @param o
* @param methodName
* @return
* @throws NoSuchFieldException
* @throws SecurityException
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
public static Object setMethod(Object o,String methodName,String value) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException{
Field field = o.getClass().getDeclaredField(methodName);
field.setAccessible(true);
field.set(o, value);
return o;
}
/**
* 属性名:格式化
* @param name
* @return
*/
public static String formatMethodName(String name){
String[] names = name.split("_");
String s = names[0];
for(int i = 1;i < names.length;i++){
s += names[i].substring(0, 1).toUpperCase()+names[i].substring(1);
}
return s;
}
//获取属性值
private static Object getMethod(Object o, String methodName) {
try {
Method get = o.getClass().getMethod(methodName);
Object result = get.invoke(o);
return result;
} catch (Exception e) {
e.getMessage();
}
return null;
}
}
action中的执行方法要包含以下代码
InputExcel<ShopInfo> ie = new InputExcel<ShopInfo>();
List<ShopInfo> list = ie.realExcel(file.get(0),ShopInfo.class);
shopService.addShops(list);