反射+注解: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.定义 ...
随机推荐
- phpmyadmin设置不密码,不登录直接进入
1.config.sample.inc.php改为config.inc.php 2.加入或更改代码: [php] $cfg['Servers'][$i]['auth_type'] = 'config' ...
- Set、Map及数组去重
https://cloud.tencent.com/developer/article/1437254 https://blog.csdn.net/weixin_34247299/article/de ...
- QT5:介绍
一.简介 QT是一个跨平台的C++开发库,主要用来开发图形用户界面(Graphical User Interface,GUI) QT除了可以绘制漂亮的界面(包括控件/布局/交互),还可以多线程/访问数 ...
- Java制作桌面弹球下载版 使用如鹏游戏引擎制作 包含2个精灵球同时弹动
package com.swift; import com.rupeng.game.GameCore; public class DesktopBouncingBall implements Runn ...
- 【卡常 bitset 分块】loj#6499. 「雅礼集训 2018 Day2」颜色
好不容易算着块大小,裸的分块才能过随机极限数据:然而这题在线的数据都竟然是构造的…… 题目描述 有 $n$ 个数字,第 $i$ 个数字为 $a_i$. 有 $m$ 次询问,每次给出 $k_i$ 个区间 ...
- MySQL 如何将Id相同的字段合并,并且以逗号隔开
数据库存的数据 sql: SELECT Id,GROUP_CONCAT(`Name` SEPARATOR ',') NAMES FROM `stu` GROUP BY Id;
- 如何把list当成栈或者队列来用
在python里,list和在C.java里的数组差不多,但是python里的list是可变长的,而且python语言也支持倒叙读取,如list[-1]可以读取最后一个元素.但这还不是最厉害的,lis ...
- stm32L011F3使用开发小记——开发坏境
今日,因工作需要,使用到了stm32L011F3芯片,此芯片基于CM0+内核,属于低功耗芯片 开发平台可以免费用于KEILMDK,keil公司用免费的许可证,网址:https://www2.keil. ...
- poj-2386 lake counting(搜索题)
Time limit1000 ms Memory limit65536 kB Due to recent rains, water has pooled in various places in Fa ...
- Linux学习-核心编译的前处理与核心功能选择
硬件环境检视与核心功能要求 根据自己的需求来确定编译的选项 保持干净原始码: make mrproper 我们还得要处理一下核心原始码底下的残留文件才行!假设我们是第一次 编译, 但是我们不清楚到底下 ...