反射+注解:excel2module
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的更多相关文章
- 【Java EE 学习 24 下】【注解在数据库开发中的使用】【反射+注解+动态代理在事务中的应用service层】
一.使用注解可以解决JavaBean和数据库中表名不一致.字段名不一致.字段数量不一致的问题. 1.Sun公司给jdbc提供的注解 @Table.@Column.@Id.@OneToMany.@One ...
- Javaweb学习笔记——(二十七)——————泛型、泛型的通配符、反射泛型信息、反射注解、注解
泛型 1.泛型类:具有一个或多个类型变量的类,称之为泛型类 class A<T>{ } 2.在创建泛型实例时,需要为其类型变量赋值 A<String> a = new ...
- 【译】8. Java反射——注解
原文地址:http://tutorials.jenkov.com/java-reflection/annotations.html ================================== ...
- JAVA-注解(2)-自定义注解及反射注解
自定义注解开发 1.开发一个注解类 开发一个注解类的过程,非常类似于开发一个接口,只不过需要通过@interface关键字来声明 2.使用元注解修饰注解的声明 所谓的原注解是用来修饰注解声明的注释,可 ...
- Java通过反射注解赋值
前段时间,领导分配一个统计销售区域汇总的数据,解决方案使用到了反射获取注解,通过注解获取属性或者设置字段属性. 问题描述 查询公司列表,分别是公司id.区域id.区域名称: 公司id 区域id 区域名 ...
- java反射--注解的定义与运用以及权限拦截
自定义注解类编写的一些规则: 1. Annotation型定义为@interface, 所有的Annotation会自动继承java.lang.Annotation这一接口,并且不能再去继承别的类或是 ...
- java反射注解妙用-获取所有接口说明
转载请注明出处:https://www.cnblogs.com/wenjunwei/p/10293490.html 前言 最近在做项目权限,使用shiro实现restful接口权限管理,对整个项目都进 ...
- Java反射+注解案例
注解类代码,注解的属性可以有多个: package reflect; import java.lang.annotation.Retention; import java.lang.annotatio ...
- 5.13Junit单元测试-反射-注解
一.Junit单元测试 * 测试分类: 1.黑盒测试:不需要写代码,给输入值,看程序是否能够输出期望的值 2.白盒测试:需要些代码的.关注程序具体的执行流程 Junit使用:白盒测试 步骤: 1.定义 ...
随机推荐
- Python面向对象进阶(二)
Python面向对象进阶2.html :first-child{margin-top:0!important}img.plugin{box-shadow:0 1px 3px rgba(0,0,0,.1 ...
- 谈谈TCP的四次挥手
“挥手”是为了终止连接,TCP四次挥手的流程图如下: (在socket编程中,可以由客户端或服务端进行close操作来进行) 下面的图是由客户端主动关闭连接 MSL是什么?最长报文段寿命 ------ ...
- 使用jquery.ajax实现省市的二级联动(SSH架构)
首先实现jquery ajax的二级联动 要下载个jquery.js 我在这里就不准备了 自行百度下载 背景介绍:通过部门的ID来查找部门下的所有班级 我实现二级联动的思路是:先查询所有部门 显示在页 ...
- Bootstrap历练实例:向列表组添加内容
向列表组添加自定义内容 我们可以向上面已添加链接的列表组添加任意的 HTML 内容.下面的实例演示了这点: <!DOCTYPE html><html><head>& ...
- abaqus中的约束
1.tie -绑定约束:作用是将模型的两部分区域绑定在一起,二者之间不发生相对运动,相当于焊在一起. 2.rigid body--刚体约束--使一个模型区域刚体化,这个区域可以是一系列节点,单元等,刚 ...
- 【Python学习之六】高阶函数1(map、reduce、filter、sorted)
1.map map()函数接收两个参数,一个是函数,一个是Iterable,map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回.示例: >>> def ...
- Voyager如何使用Compass
Compass由Resources,Commands,Logs三个部分组成 Resources包含了Links和Fonts: Commands可以执行php命令,比如创建model: 创建一个Down ...
- NodeJS基础API-path相关的问题basename,extname,dirname,parse,format,sep,delimiter,win32,posix
path 参考文档:http://nodejs.cn/api/path.html const {normalize} = require('path'); // ES6语法 // 相当于 const ...
- thinkcmf5增加微信管理app笔记
simplewind/extend/目录下增加 EasyWeChat Monolog //是PHP的一个日志类库 https://segmentfault.com/a/1190000002775 ...
- 谷歌放弃“不作恶” Alphabet要“遵守法律互相尊重”
对于一些谷歌粉而言,谷歌那条“不作恶(Don’t be evil)”的行为准则是他们引以为傲的精神信仰.这一准则于1999年被首次确认,谷歌在2004年申请上市时也提到了这一点.不过现在这一点要改变了 ...