`

反射读取解析excel模板到集合

阅读更多
#调用
List<ModelTest> list = readExcelForList(inputStream, fileName, ModelTest.class);




#excel处理工具类
public class TestUtil {


.........


public <T> List<T> readExcelForList(InputStream input, String fileName, Class<T> cls) {
		List<T> dataList = new ArrayList<T>();
		//InputStream input = null;
		try {
			//input = new FileInputStream(filePath);
			Workbook wb = null;
			if (fileName.endsWith(".xls")) {
				wb = new HSSFWorkbook(input);
			} else {
				wb = new XSSFWorkbook(input);
			}
			Sheet sheet = wb.getSheetAt(0);
			
			// 读取表头
			Row row = sheet.getRow(0);
			String[] titles = new String[]{"数据来源"};
			int rowIndex = 1;
			int rowNum= sheet.getLastRowNum();
			
			for (int i = 1; i < rowNum + 1; i++) {
				dataList.add((T) getRowValueTemplate(sheet, i, titles, AssetsMutiltm.class));
				
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				input.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return dataList;
	}
	
	static DataFormatter formatter = new DataFormatter();
	
	private <T> T getRowValueTemplate(Sheet sheet, int rowIndex, String[] columnArr, Class<T> cls) {
		Row row = sheet.getRow(rowIndex);
		T t = null;
		try {
			t = cls.newInstance();
		} catch (InstantiationException e1) {
			e1.printStackTrace();
		} catch (IllegalAccessException e1) {
			e1.printStackTrace();
		}
		Method[] methods = cls.getMethods();
		for (Method m : methods) {
			ExcelAnnotationForMethod an = m.getAnnotation(ExcelAnnotationForMethod.class);
			if (null != an) {
				for (int i = 0; i < columnArr.length; i++) {
					if (an.columnName().equals(columnArr[i])) {
						String type = an.type();
						Cell cell = row.getCell(i);
						if (null == cell) {
							cell = row.createCell(i);
						}
						try {
							if ("string".equals(type)) {
								m.invoke(t, formatter.formatCellValue(cell));
							} else if ("date".equals(type)) {
								int cellType = cell.getCellType();
								if (cellType == Cell.CELL_TYPE_STRING) {
									String value = cell.toString().trim();
									m.invoke(t, (Object) null);
								} else if (cellType == Cell.CELL_TYPE_NUMERIC) {
									Date date = cell.getDateCellValue();
									m.invoke(t, date);
								}
								
							} else if ("int".equals(type)) {
								m.invoke(t, formatter.formatCellValue(cell));
							} else {
								m.invoke(t, getCellValueTemplate(row, i));
							}
							
						} catch (IllegalArgumentException e) {
							e.printStackTrace();
						} catch (IllegalAccessException e) {
							e.printStackTrace();
						} catch (InvocationTargetException e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
		return t;
	}
	
	private Object getCellValueTemplate(Row row, int col) {
		if (row == null) {
			return "";
		}
		Cell cell = row.getCell(col);
		
		return getCellValueTemplate(cell);
	}
	
	private Object getCellValueTemplate(Cell cell) {
		if (cell == null) {
			return "";
		}else{
			Date date = null;
			String value = "";
			if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
				if(DateUtil.isCellDateFormatted(cell)){
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); 
					date = cell.getDateCellValue();
					if (null != date) {
						value = sdf.format(date);
					}
					return date;
				} else {
					value = formatter.formatCellValue(cell);
				}
			} else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
				value = formatter.formatCellValue(cell);
			} else {
				value = cell.toString().trim();
			}
			try {
				// This step is used to prevent Integer string being output with
				// '.0'.
				Float.parseFloat(value);
				value=value.replaceAll("\\.0$", "");
				value=value.replaceAll("\\.0+$", "");
				return value;
			} catch (NumberFormatException ex) {
				return value;
			}
		}

	}


.........



}





#注解类
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ExcelAnnotationForMethod {
	String columnName ();
	String type() default "string";
}







#model
public class ModelTest{
    private Long id;
    private String source;

    private int rowIndex;


    public Long getId( ){
		    return id;
    }
    public void setId(Long id){
		    this.id=id;
    }

    public String getSource( ){
		    return source;
    }
    @ExcelAnnotationForMethod(columnName="数据来源")
    public void setSource(String source){
		    this.source=source;
    }

	public int getRowIndex() {
		return rowIndex;
	}
	public void setRowIndex(int rowIndex) {
		this.rowIndex = rowIndex;
	}
    }
分享到:
评论

相关推荐

    jxls开发jar包

    2. **数据绑定**:`jxls`能够将Java对象的属性值绑定到Excel模板的单元格,这极大地简化了数据到模板的映射过程。 3. **表格操作**:支持复杂的表格操作,如合并单元格、调整行高和列宽、添加条件格式等。 4. **...

    这些年整理的一些常用Utils工具类 , 希望对大家开发有所裨益

    - 字符串格式化:类似于`format`函数,允许动态插入值到字符串模板中。 - 字符串检查:检测是否为空、是否包含特定子串、去除前后空格等。 - 分割与连接:根据分隔符分割字符串或合并字符串数组。 4. **数据类型...

    javaReport.zip

    7. **第三方库集成**:如利用Apache POI操作Excel,iText创建PDF,JasperReports设计复杂的报表模板。 8. **异常处理**:确保程序在遇到错误时能妥善处理并提供反馈。 9. **日志记录**:如何使用如Log4j或SLF4J记录...

    Spring.3.x企业应用开发实战(完整版).part2

    3.2.3 Java反射机制 3.3 资源访问利器 3.3.1 资源抽象接口 3.3.2 资源加载 3.4 BeanFactory和ApplicationContext 3.4.1 BeanFactory介绍 3.4.2 ApplicationContext介绍 3.4.3 父子容器 3.5 Bean的生命周期 3.5.1 ...

    Spring3.x企业应用开发实战(完整版) part1

    3.2.3 Java反射机制 3.3 资源访问利器 3.3.1 资源抽象接口 3.3.2 资源加载 3.4 BeanFactory和ApplicationContext 3.4.1 BeanFactory介绍 3.4.2 ApplicationContext介绍 3.4.3 父子容器 3.5 Bean的生命周期 3.5.1 ...

Global site tag (gtag.js) - Google Analytics