package test.excelTest;

 import java.io.File;
import java.io.FileInputStream;
import java.lang.reflect.Field;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List; import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
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.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; /**
* Desc:文件工具类
*/
public class FileUtil {
private static Logger logger = LoggerFactory
.getLogger(FileUtil.class); /**
* 读取xml
* @param classz
* @param fileSrc
* @return
*/
public static Object readExcel(Class classz,String fileSrc){
List list = new ArrayList<>();
int x = 0;//记录出错位置
int y = 0; try {
Workbook wb = null;
if (isExcel2003(fileSrc)){
wb = new HSSFWorkbook(new FileInputStream(new File(fileSrc)));
}else if(isExcel2007(fileSrc)){
wb = new XSSFWorkbook(new FileInputStream(new File(fileSrc)));
}
Sheet sheet = wb.getSheetAt(0); if(sheet.getLastRowNum() < 1){
return list;
} Row headRow = sheet.getRow(0); for (int i = 1; i < sheet.getLastRowNum() + 1 ; i++){
x = i;
Row row = sheet.getRow(i);
Object t = classz.newInstance(); for(int j = 0; j < row.getLastCellNum(); j++){
y = j;
Cell cellHeadFiled = headRow.getCell(j);
Cell cellFiled = row.getCell(j);
if(cellHeadFiled == null || cellFiled == null){
continue;
} String cellFiledName = null;
if(cellHeadFiled != null){
cellFiledName = cellHeadFiled.getRichStringCellValue().getString();
} cellFiled.setCellType(Cell.CELL_TYPE_STRING);
String cellFiledValue = String.valueOf(cellFiled.getRichStringCellValue()); setFiledValue(t, cellFiledName, cellFiledValue, x, y);
} list.add(t);
}
} catch (Exception e) {
e.printStackTrace();
logger.error("解析excel异常。请检查文件内容是否正确,第"+y+"行,"+(x+1)+"列出错");;
} return list;
} /**
* 设置字段值
* @param object
* @param excelFiledName
* @param value
*/
private static void setFiledValue(Object object,String excelFiledName,String value, int x, int y){
Class classz = object.getClass();
Field[] fields = classz.getDeclaredFields(); for(Field field : fields){
String filedName = field.getName();
ExcelField excelField = field.getAnnotation(ExcelField.class);
if(excelField != null){
filedName = excelField.fieldName();
} String orgFiledName = field.getType().getName();
String filedTypeName = orgFiledName.toUpperCase(); if(excelFiledName.equalsIgnoreCase(filedName)){
field.setAccessible(true);
try {
if(isNumeric(value)){
NumberFormat numberFormat = NumberFormat.getNumberInstance();
Number number = numberFormat.parse(value); if(filedTypeName.contains("INT")){
field.set(object, number.intValue());
}else if(filedTypeName.contains("DOUBLE")){
field.set(object, number.doubleValue());
}else if(filedTypeName.contains("FLOAT")){
field.set(object, number.floatValue());
}else if(filedTypeName.contains("LONG")){
field.set(object, number.longValue());
}else if(filedTypeName.contains("SHORT")){
field.set(object, number.shortValue());
}
}else {
if(filedTypeName.contains("BOOLEAN")){
field.set(object,Boolean.valueOf(value));
}else{
field.set(object,value);
}
} } catch (Exception e) {
e.printStackTrace();
logger.error("暂不支持的数据类型["+orgFiledName+"]。请检查文件内容是否正确,第"+y+"行,"+(x+1)+"列出错");
}
break;
}
}
} /**
* 判断字符串是否为数字
* @param str
* @return
*/
public static boolean isNumeric(String str){
if(StringUtils.isEmpty(str)){
return false;
} for (int i = str.length();--i>=0;){
if (!Character.isDigit(str.charAt(i))){
return false;
}
}
return true;
} public static boolean isExcel2003(String filePath)
{ return filePath.matches("^.+\\.(?i)(xls)$"); }
public static boolean isExcel2007(String filePath)
{ return filePath.matches("^.+\\.(?i)(xlsx)$"); } public static void main(String[] args) throws Exception {
String sre = "D://b.xls";
Object result = readExcel(Person.class, sre);
List<Person> list = (List<Person>) result;
for(Person person : list){
System.out.println("姓名:"+person.getName()+"---年龄:"+person.getAge()+"---性别:"+person.getSex());
} } }
 package test.excelTest;

 import java.lang.annotation.*;  

 /**
* Desc:Excel字段名
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ExcelField { public String fieldName();
}
 package test.excelTest;

 /**
* Desc: module
*/
public class Person { @ExcelField(fieldName="名字")
private String name; @ExcelField(fieldName="年龄")
private double age; @ExcelField(fieldName="性别")
private String sex; public Person(){ } public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public double getAge() {
return age;
} public void setAge(double age) {
this.age = age;
} public String getSex() {
return sex;
} public void setSex(String sex) {
this.sex = sex;
}
}

反射+注解:excel2module的更多相关文章

  1. 【Java EE 学习 24 下】【注解在数据库开发中的使用】【反射+注解+动态代理在事务中的应用service层】

    一.使用注解可以解决JavaBean和数据库中表名不一致.字段名不一致.字段数量不一致的问题. 1.Sun公司给jdbc提供的注解 @Table.@Column.@Id.@OneToMany.@One ...

  2. Javaweb学习笔记——(二十七)——————泛型、泛型的通配符、反射泛型信息、反射注解、注解

    泛型     1.泛型类:具有一个或多个类型变量的类,称之为泛型类 class A<T>{ } 2.在创建泛型实例时,需要为其类型变量赋值 A<String> a = new ...

  3. 【译】8. Java反射——注解

    原文地址:http://tutorials.jenkov.com/java-reflection/annotations.html ================================== ...

  4. JAVA-注解(2)-自定义注解及反射注解

    自定义注解开发 1.开发一个注解类 开发一个注解类的过程,非常类似于开发一个接口,只不过需要通过@interface关键字来声明 2.使用元注解修饰注解的声明 所谓的原注解是用来修饰注解声明的注释,可 ...

  5. Java通过反射注解赋值

    前段时间,领导分配一个统计销售区域汇总的数据,解决方案使用到了反射获取注解,通过注解获取属性或者设置字段属性. 问题描述 查询公司列表,分别是公司id.区域id.区域名称: 公司id 区域id 区域名 ...

  6. java反射--注解的定义与运用以及权限拦截

    自定义注解类编写的一些规则: 1. Annotation型定义为@interface, 所有的Annotation会自动继承java.lang.Annotation这一接口,并且不能再去继承别的类或是 ...

  7. java反射注解妙用-获取所有接口说明

    转载请注明出处:https://www.cnblogs.com/wenjunwei/p/10293490.html 前言 最近在做项目权限,使用shiro实现restful接口权限管理,对整个项目都进 ...

  8. Java反射+注解案例

    注解类代码,注解的属性可以有多个: package reflect; import java.lang.annotation.Retention; import java.lang.annotatio ...

  9. 5.13Junit单元测试-反射-注解

    一.Junit单元测试 * 测试分类: 1.黑盒测试:不需要写代码,给输入值,看程序是否能够输出期望的值 2.白盒测试:需要些代码的.关注程序具体的执行流程 Junit使用:白盒测试 步骤: 1.定义 ...

随机推荐

  1. Problem A: 文件操作--二进制文件读入

    Problem A: 文件操作--二进制文件读入 Time Limit: 1 Sec  Memory Limit: 128 MBSubmit: 1952  Solved: 524[Submit][St ...

  2. Python 继承实现的原理(继承顺序)

    继承顺序 Python3 : 新式类的查找顺序:广度优先 新式类的继承: class A(object): Python2 3 都是了 MRO算法--生成一个列表保存继承顺序表 不找到底部 Pytho ...

  3. Dapper学习总结

    看了<Dapper从入门到精通>后的总结 (1)Dapper 是直接扩展 IDBConnection,而且是单独一个文件,可以直接嵌入到项目中使用. (2)通过手写sql语句,调用exec ...

  4. Bootstrap 徽章(Badges)

    本章将讲解Bootstrap徽章(Badges),徽章与标签相似,主要的区别是徽章的圆角比较圆滑. 徽章(Badges)主要用于突出显示新的或未读的项,如果使用徽章,只需要把<span clas ...

  5. cnpm 莫名奇妙bug 莫名奇妙的痛

    cnpm 莫名奇妙bug 莫名奇妙的痛 最近想搭建react@v16 和 react-router@v4,搭建过程打算用vue脚手架webpack模板那套配置方法(webpack3). 由于我之前安装 ...

  6. DNS 工作原理是什么,域名劫持、域名欺骗、域名污染又是什么

    DNS 工作原理是什么,域名劫持.域名欺骗.域名污染又是什么 2014年11月27日 10:05:40 阅读数:6726 标签: dns网络互联网顶级域名递归 更多 个人分类: 网络学习   一.DN ...

  7. python处理excel总结

    工作中,大家经常会使用excel去处理数据以及展示,但是对于部分工作我们可以借助程序帮忙实现,达到高效解决问题的效果,比如将接口返回的json解析并保存结果到excel中,按一定规律处理excel中的 ...

  8. day3-python 登录

    import datetime # 1. f = open('users') result = f.read() f.close() user_list = result.split() # user ...

  9. 模拟发送http请求的工具推荐

    做网站开发时,经常需要发送请求来测试自己的代码是否OK,这时候模拟发送http请求的工具就起到了很大的作用.特别是需要在请求带header时就更加的有必要使用工具.下面推荐的工具有的是基于系统开发的程 ...

  10. classpath、WEB-INF

    classpath是指 WEB-INF文件夹下的classes目录(war包),对于springboot项目打包出来的jar包,里面的就是BOOT-INF: 这个demo的源码结构如下: 可见,jav ...