当前位置: 移动技术网 > IT编程>软件设计>架构 > Java解析Excel之应用Reflection等技术实现动态读取

Java解析Excel之应用Reflection等技术实现动态读取

2018年09月24日  | 移动技术网IT编程  | 我要评论

 目录树

  • 背景
  • 技术选型
  • 问题分析
  • 技术要点及难点分析
  • 源码分析
  • 测试用例

 


 

背景

tip:因为产品提的需求我都开发完了,进行了项目提测;前天老大走过来说:你用spring-boot开发一个解析excel的jar包.....详细对话如下:

a:世生,你用spring-boot开发一个解析excel的jar包。

b:为什么不在原来的项目上进行开发呢?(很纳闷,这个东西不是一般用于前端上传数据的嘛,这是后端层,咋搞这个)

a:因为xxxx这个需求有比较多的数据需要初始化,这个jar是作为一个上线的数据初始化脚本

b:嗯,好的

 


 

技术选型

   毕竟是第一次写解析excel代码,问了度娘说是有两种方式可以做到。一是利用wso2的jxl解析二是利用apache的poi解析;我去maven repository官网搜索了这两个jar包,对比了下jml的最新版本是2.6.12竟然是2011.05月更新的,而poi的最新版本是4.0.x是2018.08更新的;个人觉得jml最新版本都是2011.05更新的,相对于apache的poi包来说更不靠谱;不断持续更新的开源项目或者开源jar包不管是bug还是兼容性相对来说是越来越好。所以最终选定用apache大佬的poi进行开发。

 


 

问题分析

  解析excel的关键点是在于从excel表格中读取数据到内存(解析excel),然后可能是校验数据、通过业务逻辑分析数据、最终持久化到数据库中;其实这其中最重要的不是解析excel,而是将解析出的数据持久化到数据库中以备有用之需。而解析excel的这块功能只能算是一个util类,不能与业务代码耦合一起;然后我看到很多的excel解析相关的代码都是在解析数据中混淆业务代码逻辑,其实这些都是不可取的,这会导致解析excel逻辑与业务逻辑相耦合也就是冗杂、代码重用率低、可扩展性低等问题。因为之前在做项目的时候遇到过一个问题:我负责的模块是一个中间模块(通讯采用dubbo),其他系统要依赖我这个接口进行请求的转发可我调用其他系统返回的结果对象却各个都不同,我叫其他系统负责人说要统一调用接口返回的对象,但是其他系统的负责人都不是同一个人执行起来效率太低了,在历经一个星期都无果的情况下我只能撒下自己的杀手锏了;在这种极端条件下最终我不管其他数据的接口返回的对象是什么,我直接用object接收返回类型,通过反射获取决定请求成功与否的属性值(欣慰的是当时必传属性值倒是一样的)。通过这种方法我可以少些很多的代码(当时其他系统有15+),不然的话每调用不同系统的接口我都需要进行逻辑判断或者是干脆对于调用他们不同的系统我采用不同接口进行转发,但选用这种方法却便利多了。

  以上问题分析及一个场景的描述很好理解,但是通过object接收返回信息得这个场景事实上却有所欠佳;返回对象不同的这个问题最好的处理方案就是统一接口,我那个方案是在需求推动但别人无法及时配合的极端条件下使用的,是没办法中的办法,但这也是一个没有办法中的一个最优的处理方案,兼容性比较强。以下我就用图来分析这两种情况的比较:

  1.非动态模式:将excel数据加载到内存与业务代码逻辑混合,数据在解析期间交叉传递。弊端:每新增一个需要解析的excel,解析excel代码块就需要重新开发,代码复用率底下、可扩展性也低。

  

 

  2.动态模式:将excel数据加载到内存与业务代码逻辑分开;excel数据加载到内存之后才将数据传递给业务代码逻辑处理,解析excel与业务代码之间分开;优点:将解析excel的这部分代码封装为一个excelutil,代码复用率明显提高,而且解析与业务代码间实行解耦,可扩展性增强。

       


 

技术要点及难点分析

  要实现动态解析,实现解析与业务代码逻辑相解耦;那么我们不难会想起一个java的一个关键技术-reflection(反射原理),python、ruby等是动态语言而理论上java是一门静态语言,但是java引入了reflection技术实现了动态性。反射原理我们都比较熟悉,就是在运行期间动态获取类的所有属性及其方法,可以对这些数据进行相关的操作。以上动态解析excel的实现就需要用到java这项的高级技术了,通过这项技术可以实现动态解析、解析与业务逻辑解耦等。为了实现动态解析的目的我应用了java反射技术,但是在开发的过程我发现反射执行一行数据结束的时候如何保存呢?换句话说就是:解析的时候一行的excel数据封装后就是一个bean,一个excel表格就是多个bean 即“beans”;如果我们直接将反射执行后的结果保存至list中,当解析整个excel结束后我们会发现,整个list里面的对象的值完全一样的?what?这是什么原因导致的呢?这就是类似于:object obj=new object(),我们每次解析都只是把 obj 放在list中,list中的每一个对象都是同一个 obj(引用不变,实例也不变),所以自然也就相同了;因为当一个类执行反射的时候其实它的运行时状态只有一个,也就是类似于只有一个实例,而传统的解析excel是解析出一条数据就new一个对象进行封装数据,然后将bean存放至list。然而有什么方法能够解决这一类问题呢?那就是object 的native clone()方法了,clone()这个大佬是比较牛逼的一个人物,在不创建对象的情况下将属性值复制给另一个对象,具体实现需要实现cloneable接口并重写clone()。而解决这个问题的方式就是在每解析完一行excel数据的时候,反射调用该对象的clone方法。动态解析具体实现应用了apache poi、 lrucache(lru缓存)、reflection(反射)、java的clone等技术。如果以上技术没有了解过的朋友可以去自行了解,这里不加赘述。

  前提条件:因为要实现动态解析,动态设置值,那么我们在反射执行set操作的时候就需要知道相应的setmethod(),那么我们可以在excel规定第一行就是属性字段,并且字段名称跟bean的名称一样,读取的时候先把第一行的数据放在一个string []数组中。具体实现请参照以下源码。我已经把相关代码打包成jar,需要的朋友可以自行下载;jar包下载链接:https://pan.baidu.com/s/1fkcch54s3zthfv66t2pk2w 密码:nur8

  使用方法:新建bean用于存储excel数据信息,每个属性需要有get、set操作,属性与excel首行相同,最重要的一点是要实现clonesble接口重写clone方法excel使用office编辑,亲测wps编辑的excel某些属性值有问题。在new readexcelutil 的时候只需要将对象类型与excel文件路径传入构造函数即可,然后调用 readexcelutil的getobjectlist即可得到解析后的所有对象。至于这个对象你可以用任何的对象,你可以换成teacher、orderinfo、userinfo......但是前面提到的:excel第一行的属性字段需要与bean的属性字段一致,否则无法调用目标方法,具体可参见reflectioninitvalue的方法。具体实现请参见:文章末尾的test类测试。 

 


 

 源码分析

  • 前提条件:引入apache poi 的maven仓库坐标,我这里使用的是3.25版本的。

 


1 <!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
 2 <dependency>
 3     <groupid>org.apache.poi</groupid>
 4     <artifactid>poi</artifactid>
 5     <version>3.15</version>
 6 </dependency>
 7 <dependency>
 8     <groupid>org.apache.poi</groupid>
 9     <artifactid>poi-ooxml</artifactid>
10     <version>3.15</version>
11 </dependency>

 

  • 主要类:common.java、lrucache.java、lrucacheexception.java、resolvefileexception.java、readexcelutil.java、reflectioninitvalue.java、student、test
  • common.java:基础常量池,主要用于反射执行method方法时判断method的参数类型的常量。

 

 1 package com.hdbs.common;
 2 
 3 /**
 4  * @author :cnblogs-windsjune
 5  * @version :1.1.0
 6  * @date :2018年9月20日 下午6:33:54
 7  * @comments :解析excel公共类常量类
 8  */
 9 
10 public class common {
11     
12     public static final string office_excel_2003_postfix_xls = "xls";
13     public static final string office_excel_2010_postfix_xlsx = "xlsx";
14     public static final string data_type_long ="long";
15     public static final string data_type_boolean ="boolean";
16     public static final string data_type_int ="int";
17     public static final string data_type_float ="float";
18     public static final string data_type_double ="double";
19     public static final string data_type_long ="class java.lang.long";
20     public static final string data_type_integer ="class java.lang.integer";
21 
22 
23 }

 

 

  • lrucacheexception.java;lru缓存自定义异常类。
 1 package com.hdbs.exceptions;
 2 
 3 /**
 4  * creater: cnblogs-windsjune
 5  * date: 2018/9/21
 6  * time: 10:04
 7  * description: no description
 8  */
 9 public class lrucacheexception extends  exception{
10     /**
11      * 错误码
12      */
13     private string errorcode;
14 
15     /**
16      * 错误描述
17      */
18     private string errormessage;
19 
20     public lrucacheexception(string errorcode, string errormessage) {
21         this.errorcode = errorcode;
22         this.errormessage = errormessage;
23     }
24 
25     public lrucacheexception(string message) {
26         super(message);
27         this.errormessage = errormessage;
28     }
29 
30     public string geterrorcode() {
31         return errorcode;
32     }
33 
34     public void seterrorcode(string errorcode) {
35         this.errorcode = errorcode;
36     }
37 
38     public string geterrormessage() {
39         return errormessage;
40     }
41 
42     public void seterrormessage(string errormessage) {
43         this.errormessage = errormessage;
44     }
45 }

 

  • resolvefileexception.java;解析excel自定义异常类。

 

 1 package com.hdbs.exceptions;
 2 /**
 3  * creater: cnblogs-windsjune
 4  * date: 2018/9/20
 5  * time: 19:44
 6  * description: 解析excel的公共异常类
 7  */
 8 
 9 public class resolvefileexception extends runtimeexception{
10 
11     /**
12      * 错误码
13      */
14     private string errorcode;
15 
16     /**
17      * 错误描述
18      */
19     private string errormessage;
20 
21     public resolvefileexception(string errorcode, string errormessage) {
22         this.errorcode = errorcode;
23         this.errormessage = errormessage;
24     }
25 
26     public resolvefileexception(string message) {
27         super(message);
28         this.errormessage = errormessage;
29     }
30 
31     public string geterrorcode() {
32         return errorcode;
33     }
34 
35     public void seterrorcode(string errorcode) {
36         this.errorcode = errorcode;
37     }
38 
39     public string geterrormessage() {
40         return errormessage;
41     }
42 
43     public void seterrormessage(string errormessage) {
44         this.errormessage = errormessage;
45     }
46 }

 

 

  • lrucache.java:lru缓存池,主要用于不同线程反射获取的methods,减少相同线程反射执行次数,减轻应用的负载、提高执行效率。我这里是基于linkedhashmap实现的lru缓存,你也可以用数组或者其他方式实现该算法。以下代码逻辑如果不能理解的可以先去了解linkedhashset的源码。

 

 1 package com.hdbs.common;
 2 
 3 import com.hdbs.exceptions.lrucacheexception;
 4 import org.slf4j.logger;
 5 import org.slf4j.loggerfactory;
 6 
 7 import java.lang.reflect.method;
 8 import java.util.linkedhashmap;
 9 import java.util.map;
10 
11 /**
12  * creater: cnblogs-windsjune
13  * date: 2018/9/20
14  * time: 19:44
15  * description: linkedhashmap实现lru缓存不同线程反射获取的method方法
16  */
17 public class lrucache {
18     private  static  final logger logger=loggerfactory.getlogger(lrucache.class);
19     //缓存容量
20     private static final int cachesize = 10;
21 
22     private static final map<integer,method[]> cachemap = new linkedhashmap<integer, method[]>((int) math.ceil(cachesize / 0.75f) + 1, 0.75f, true){
23         @override
24         protected boolean removeeldestentry(map.entry<integer,method[]> eldest){
25 
26             return  size()> cachesize;
27             
28         }
29     };
30 
31     /**
32      * 设置缓存
33      * @param key
34      * @param methods
35      * @return boolean
36      */
37     public static boolean set (integer key,method [] methods) throws lrucacheexception {
38         try {
39                cachemap.put(key,methods);
40                return true;
41         }
42         catch ( exception e ){
43               throw new lrucacheexception("set lru缓存异常!");
44         }
45     }
46 
47     /**
48      * 获取缓存的method
49      * @param key
50      * @return method
51      */
52     public static method[] get(integer key) throws lrucacheexception {
53         method[] methods=null;
54         try {
55             methods=cachemap.get(key);
56         }catch ( exception e ){
57                throw new lrucacheexception("get lru缓存异常!{}");
58         }
59         return methods;
60     }
61 }

 

 

  • readexcelutil.java;解析excel数据工具类(将excel加载到内存)

 

  1 package com.hdbs.resolver;
  2 
  3 import com.hdbs.common.common;
  4 import com.hdbs.exceptions.resolvefileexception;
  5 import org.apache.commons.lang3.stringutils;
  6 import org.apache.poi.hssf.usermodel.hssfcell;
  7 import org.apache.poi.hssf.usermodel.hssfrow;
  8 import org.apache.poi.hssf.usermodel.hssfsheet;
  9 import org.apache.poi.hssf.usermodel.hssfworkbook;
 10 import org.apache.poi.xssf.usermodel.xssfcell;
 11 import org.apache.poi.xssf.usermodel.xssfrow;
 12 import org.apache.poi.xssf.usermodel.xssfsheet;
 13 import org.apache.poi.xssf.usermodel.xssfworkbook;
 14 import org.slf4j.logger;
 15 import org.slf4j.loggerfactory;
 16 
 17 import java.io.file;
 18 import java.io.fileinputstream;
 19 import java.io.ioexception;
 20 import java.io.inputstream;
 21 import java.lang.reflect.invocationtargetexception;
 22 import java.util.arraylist;
 23 import java.util.hashmap;
 24 import java.util.list;
 25 import java.util.map;
 26 
 27 /**
 28  * @author :cnblogs-windsjune
 29  * @version :1.1.0
 30  * @date :2018年9月20日 下午6:13:43
 31  * @comments :
 32  */
 33 
 34 public class readexcelutil {
 35 
 36     private static final logger logger = loggerfactory.getlogger(readexcelutil.class);
 37   //存放属性集
 38     private  map<integer,string []> fieldsmap=new hashmap<>();
 39   //存放解析后的对象list
 40     private list<object> objectslist = new arraylist<>();
 41   //反射运行时对象
 42     private object object=null;
 43   //excel文件路径
 44     private  string path =null;
 45   //获取解析后的对象集
 46     public list<object> getobjectslist() {
 47         return this.objectslist;
 48     }
 49 
 50     public readexcelutil(object object,string path) throws invocationtargetexception, nosuchmethodexception, instantiationexception, illegalaccessexception, ioexception {
 51         this.object=object;
 52         this.path=path;
 53         readexcel();
 54     }
 55 
 56     /**
 57      * 添加object到list中
 58      * @param object
 59      * @return
 60      */
 61     public boolean addlistobject(object object){
 62         boolean issucceed=this.objectslist.add(object);
 63         return  issucceed;
 64     }
 65 
 66     /**
 67      * 读取excel,判断是xls结尾(2010之前);还是xlsx结尾(2010以后)的excel
 68      * 
 69      * @return
 70      * @throws ioexception
 71      */
 72     public boolean readexcel() throws ioexception, instantiationexception, illegalaccessexception, nosuchmethodexception, invocationtargetexception {
 73         if (stringutils.isempty(path)) {
 74             return false;
 75         } else {
 76             // 截取后缀名,判断是xls还是xlsx
 77             string postfix = path.substring(path.lastindexof(".") + 1);
 78             if (!stringutils.isempty(postfix)) {
 79                 if (common.office_excel_2003_postfix_xls.equals(postfix)) {
 80                     return readxls();
 81                 } else if (common.office_excel_2010_postfix_xlsx.equals(postfix)) {
 82                     return readxlsx();
 83                 }
 84             } else {
 85                 logger.error("文件后缀名有误!");
 86                 throw new resolvefileexception("文件后缀名有误!" + "[" + path + "]");
 87             }
 88         }
 89         return false;
 90     }
 91 
 92     /**
 93      * 读取xls(2010)之后的excel
 94      * 
 95      * @return
 96      * @throws ioexception
 97      */
 98     public  boolean readxlsx() throws ioexception{
 99         file file = new file(path);
100         inputstream is = new fileinputstream(file);
101         xssfworkbook xssfworkbook = new xssfworkbook(is);
102         // 遍历sheet页
103         for (int numsheet = 0; numsheet < xssfworkbook.getnumberofsheets(); numsheet++) {
104             xssfsheet xssfsheet = xssfworkbook.getsheetat(numsheet);
105             string [] fields=null;
106             if (xssfsheet == null) {
107                 continue;
108             }
109             // 循环行
110             for (int rownum = 0; rownum <= xssfsheet.getlastrownum(); rownum++) {
111                 xssfrow xssfrow = xssfsheet.getrow(rownum);
112                 int cloumns=xssfrow.getlastcellnum();
113                 int i=0;
114                 //获取第一行的所有属性
115                 if (rownum == 0){
116                     fields=getfields(xssfrow,cloumns);
117                     fieldsmap.put(numsheet,fields);
118                     continue;
119                 }
120                 //遍历数据,反射set值
121                 while (i<cloumns){
122                     xssfcell field=xssfrow.getcell(i);
123                     string value=getvalue(field);
124                     try {
125                         reflectioninitvalue.setvalue(object,fields[i],value);
126                     }catch ( exception e ){
127                         throw new resolvefileexception(e.getmessage());
128                     }
129                     i++;
130                 }
131                 //通过反射执行clone复制对象
132                 object result=reflectioninitvalue.invokeclone(object,"clone");
133                 this.addlistobject(result);
134                // system.out.println(object.tostring());
135             }
136         }
137         return true;
138     }
139 
140     /**
141      * 读取xls(2010)之前的excel
142      * 
143      * @return
144      * @throws ioexception
145      */
146     public boolean readxls() throws ioexception, resolvefileexception {
147         inputstream is = new fileinputstream(path);
148         hssfworkbook hssfworkbook = new hssfworkbook(is);
149         // 遍历sheet页
150         for (int numsheet = 0; numsheet < hssfworkbook.getnumberofsheets(); numsheet++) {
151             hssfsheet hssfsheet = hssfworkbook.getsheetat(numsheet);
152             string[] fields = null;
153             if (hssfsheet == null) {
154                 continue;
155             }
156             // 循环行row
157             for (int rownum = 0; rownum <= hssfsheet.getlastrownum(); rownum++) {
158                 hssfrow hssfrow = hssfsheet.getrow(rownum);
159                 int cloumns=hssfrow.getlastcellnum();
160                 int i=0;
161                 //获取第一行的所有属性
162                 if (rownum == 0){
163                     //获取属性字段
164                     fields=getfields(hssfrow,cloumns);
165                     fieldsmap.put(numsheet,fields);
166                     continue;
167                 }
168                 //遍历数据,反射set值
169                 while (i<cloumns){
170                     hssfcell field=hssfrow.getcell(i);
171                     string value=getvalue(field);
172                     try {
173                         reflectioninitvalue.setvalue(object,fields[i],value);
174                     }catch ( exception e ){
175                         throw  new resolvefileexception(e.getmessage());
176                     }
177                     i++;
178                 }
179                 //通过反射执行clone复制对象
180                 object result=reflectioninitvalue.invokeclone(object,"clone");
181                 this.addlistobject(result);
182             }
183         }
184         return true;
185     }
186 
187     /**
188      * xlsx -根据数据类型,获取单元格的值
189      * @param xssfrow
190      * @return
191      */
192     @suppresswarnings({ "static-access" })
193     private static string getvalue(xssfcell xssfrow) {
194         string value=null;
195         try {
196             if (xssfrow.getcelltype() == xssfrow.cell_type_boolean) {
197                 // 返回布尔类型的值
198                 value=string.valueof(xssfrow.getbooleancellvalue()).replace(" ","");
199             } else if (xssfrow.getcelltype() == xssfrow.cell_type_numeric) {
200                 // 返回数值类型的值
201                 value= string.valueof(xssfrow.getnumericcellvalue()).replace(" ","");
202             } else {
203                 // 返回字符串类型的值
204                 value= string.valueof(xssfrow.getstringcellvalue()).replace(" ","");
205             }
206         } catch (exception e) {
207             //单元格为空,不处理
208             value=null;
209             logger.error("单元格为空!");
210         }
211         return value;
212     }
213 
214     /**
215      * xls-根据数据类型,获取单元格的值
216      * @param hssfcell
217      * @return
218      */
219     @suppresswarnings({ "static-access" })
220     private static string getvalue(hssfcell hssfcell) {
221         string value=null;
222         try {
223             if (hssfcell.getcelltype() == hssfcell.cell_type_boolean) {
224                 // 返回布尔类型的值
225                 value=string.valueof(hssfcell.getbooleancellvalue()).replaceall(" ","");
226             } else if (hssfcell.getcelltype() == hssfcell.cell_type_numeric) {
227                 // 返回数值类型的值
228                 value=string.valueof(hssfcell.getnumericcellvalue()).replaceall(" ","");
229             } else {
230                 // 返回字符串类型的值
231                 value=string.valueof(hssfcell.getstringcellvalue()).replaceall(" ","");
232             }
233         } catch (exception e) {
234             //单元格为空,不处理
235             value=null;
236             logger.error("单元格为空!");
237         }
238         return value;
239     }
240 
241     /**
242      * xls excel文件类型获取属性(2010之前)
243      * @param cloumns
244      * @return string[]
245      */
246     private  static string[] getfields (hssfrow hssfrow,int cloumns){
247         string [] fields=new string[cloumns];
248         int i=0;
249         try {
250             while (i<cloumns){
251                 hssfcell field=hssfrow.getcell(i);
252                 string value=getvalue(field);
253                 fields[i]=value.trim();
254                 i++;
255             }
256         }catch ( exception e){
257             throw  new resolvefileexception("获取属性集失败!");
258         }
259         return  fields;
260     }
261 
262     /**
263      * xlsx excel文件类型获取属性(2010之后)
264      * @param cloumns
265      * @return string[]
266      */
267     private  static string[] getfields(xssfrow xssfrow,int cloumns){
268         string [] fields=new string[cloumns];
269         int i=0;
270         try {
271             while (i<cloumns){
272                 xssfcell field=xssfrow.getcell(i);
273                 string value=getvalue(field);
274                 fields[i]=value.trim();
275                 i++;
276             }
277         }catch ( exception e ){
278             throw  new resolvefileexception("获取属性集失败!");
279         }
280         return  fields;
281     }
282 
283 }

 

  • reflectioninitvalue.java;
  1 package com.hdbs.resolver;
  2 
  3 import com.hdbs.common.common;
  4 import com.hdbs.common.lrucache;
  5 import com.hdbs.exceptions.lrucacheexception;
  6 import com.hdbs.exceptions.resolvefileexception;
  7 
  8 import java.lang.reflect.invocationtargetexception;
  9 import java.lang.reflect.method;
 10 import java.lang.reflect.type;
 11 
 12 /**
 13  * creater: cnblogs-windsjune
 14  * date: 2018/9/21
 15  * time: 9:54
 16  * description: no description
 17  */
 18 public class reflectioninitvalue {
 19 
 20     private static int threadhashcodekey=thread.currentthread().tostring().hashcode();
 21 
 22     /**
 23      * 通过反射动态将excel读取的信息设置到对应的bean中
 24      *
 25      * @param object-存储对象bean
 26      * @param key-属性参数名
 27      * @param value-属性值
 28      * @throws exception
 29      */
 30     public static void setvalue(object object, string key, string value) throws lrucacheexception {
 31         string methodname = null;
 32         string paramtype = null;
 33         method[] methods = null;
 34         if (lrucache.get(threadhashcodekey) == null) {
 35             class<?> clazz = object.getclass();
 36             methods = clazz.getdeclaredmethods();
 37             lrucache.set(threadhashcodekey, methods);
 38         } else {
 39             methods = lrucache.get(threadhashcodekey);
 40         }
 41         for (method method : methods) {
 42             methodname = method.getname();
 43             if (methodname.startswith("set") && methodname.tolowercase().equals("set" + key.tolowercase())) {
 44                 type[] types = method.getgenericparametertypes();
 45                 for (type type : types) {
 46                     paramtype = type.tostring();
 47                     // 根据参数类型转化value,并进行set操作
 48                     excuteinvokesetvalue(object, method, paramtype, value, 0);
 49                 }
 50                 // 该属性已经执行setvalue操作,无需循环
 51                 break;
 52             }
 53         }
 54     }
 55 
 56     /**
 57      * 初始化对象bean
 58      *
 59      * @param object
 60      * @throws exception
 61      */
 62     public static void initbeans(object object) throws resolvefileexception, lrucacheexception {
 63         // class<?> clazz = object.getclass();
 64         string methodname = null;
 65         string paramtype = null;
 66         method[] methods = lrucache.get(threadhashcodekey);
 67         try {
 68             for (method method : methods) {
 69                 methodname = method.getname();
 70                 if (methodname.startswith("set")) {
 71                     type[] types = method.getgenericparametertypes();
 72                     for (type type : types) {
 73                         paramtype = type.getclass().getname();
 74                     }
 75                     // 根据参数类型转化value,并进行set初始化属性值
 76                     excuteinvokesetvalue(object, method, paramtype, "", 1);
 77                 }
 78             }
 79         } catch (exception e) {
 80             throw new resolvefileexception("初始化bean错误!method:[ " + methodname + " ]");
 81         }
 82     }
 83 
 84     /**
 85      * 根据参数类型转化value,并进行set操作
 86      *
 87      * @param object-存储对象bean
 88      * @param method-执行的set对应属性的方法
 89      * @param paramtype-属性参数类型
 90      * @param value-属性值
 91      * @param operationtype-操作类型(0-设置属性,1-初始化bean)
 92      * @throws exception
 93      */
 94     public static void excuteinvokesetvalue(object object, method method, string paramtype, string value,
 95                                              int operationtype){
 96         try {
 97             switch (paramtype) {
 98                 case common.data_type_long: {// 参数属性long
 99                     if (value !=null && value.contains(".")){
100                         value=value.substring(0,value.lastindexof("."));
101                     }
102                     long temp = long.valueof(operationtype == 0 && value !=null ? value : "0");
103                     method.invoke(object, temp);
104                     break;
105                 }
106                 case common.data_type_boolean: {// 参数属性boolean
107                     boolean temp = (operationtype == 0 ? (boolean.valueof(value != null ? value:"false")) : false);
108                     method.invoke(object, temp);
109                     break;
110                 }
111                 case common.data_type_int: {// 参数属性int
112                     if (value !=null && value.contains(".")){
113                         value=value.substring(0,value.lastindexof("."));
114                     }
115                     int temp = integer.valueof(operationtype == 0 && value!=null ? value : "0");
116                     method.invoke(object, temp);
117                     break;
118                 }
119                 case common.data_type_float: {// 参数属性float
120                     if (value !=null && value.contains(".")){
121                         value=value.substring(0,value.lastindexof("."));
122                     }
123                     float temp = float.valueof(operationtype == 0 && value !=null ? value : "0");
124                     method.invoke(object, temp);
125                     break;
126                 }
127                 case common.data_type_double: {// 参数属性double
128                     double temp = double.valueof(operationtype == 0 && value !=null ? value : "0");
129                     method.invoke(object, temp);
130                     break;
131                 }
132                 case common.data_type_long: {// 参数属性long
133                     if (value !=null && value.contains(".")){
134                         value=value.substring(0,value.lastindexof("."));
135                     }
136                     long temp = long.valueof(operationtype == 0 && value!=null ? value : "0");
137                     method.invoke(object, temp);
138                     break;
139                 }
140                 case common.data_type_integer: {// 参数属性integer
141                     if (value !=null && value.contains(".")){
142                         value=value.substring(0,value.lastindexof("."));
143                     }
144                     int temp = integer.valueof(operationtype == 0 && value!=null ? value : "0");
145                     method.invoke(object, temp);
146                     break;
147                 }
148                 default: {// 参数属性string
149                     if (value !=null && value.contains(".")){
150                         value=value.substring(0,value.lastindexof("."));
151                     }
152                     method.invoke(object, operationtype == 0 ? value : null);
153                     break;
154                 }
155             }
156 
157         } catch ( illegalaccessexception e ) {
158             throw new resolvefileexception("invoke方法错误![method:" + method.getname() + " [value:" + value + " ]");
159         } catch ( invocationtargetexception e ) {
160             throw new resolvefileexception("invoke方法错误![method:" + method.getname() + " [value:" + value + " ]");
161         } catch (exception e) {
162             throw new resolvefileexception("字段属性错误![method:" + method.getname() + " [value:" + value + " ]");
163         }
164 
165 
166     }
167 
168     /**
169      *
170      * @param object
171      * @param methodname
172      * @return
173      * @throws resolvefileexception
174      */
175     public static object invokeclone (object object,string methodname){
176         class clazz=object.getclass();
177         try {
178             method method=clazz.getmethod(methodname);
179             object result=method.invoke(object);
180             return  result;
181         }catch ( exception e ){
182             throw new resolvefileexception("解析excel,反射执行set操作异常!");
183         }
184 
185     }
186 
187 
188 }

 

  • student.java;用于存储数据信息得bean。
  1 package com.hdbs.beans;
  2 
  3 import java.util.arraylist;
  4 import java.util.list;
  5 
  6 /**
  7  * @author :windsjune/博客园:windsjune
  8  * @version :1.1.0
  9  * @date :2018年9月20日 下午6:05:57
 10  * @comments :
 11  */
 12 
 13 public class student implements cloneable{
 14     
 15     /**
 16      * id
 17      */
 18     private integer id;
 19     /**
 20      * 学号
 21      */
 22     private string no;
 23     /**
 24      * 姓名
 25      */
 26     private string name;
 27     /**
 28      * 学院
 29      */
 30     private string age;
 31     /**
 32      * 成绩
 33      */
 34     private float score;
 35 
 36     /**
 37      * 地址
 38      */
 39     private string adress;
 40 
 41     private list<student> studentslist=new arraylist<>();
 42 
 43     public integer getid() {
 44         return id;
 45     }
 46 
 47     public void setid(integer id) {
 48         this.id = id;
 49     }
 50 
 51     public string getno() {
 52         return no;
 53     }
 54 
 55     public void setno(string no) {
 56         this.no = no;
 57     }
 58 
 59     public string getname() {
 60         return name;
 61     }
 62 
 63     public void setname(string name) {
 64         this.name = name;
 65     }
 66 
 67     public string getage() {
 68         return age;
 69     }
 70 
 71     public void setage(string age) {
 72         this.age = age;
 73     }
 74 
 75     public float getscore() {
 76         return score;
 77     }
 78 
 79     public void setscore(float score) {
 80         this.score = score;
 81     }
 82 
 83     public string getadress() {
 84         return adress;
 85     }
 86 
 87     public void setadress(string adress) {
 88         this.adress = adress;
 89     }
 90 
 91     public list<student> getstudentslist() {
 92         return studentslist;
 93     }
 94 
 95     public object clone() throws clonenotsupportedexception{
 96         return super.clone();
 97     }
 98 
 99     @override
100     public string tostring() {
101         return "student{" +
102                 "id=" + id +
103                 ", no='" + no + '\'' +
104                 ", name='" + name + '\'' +
105                 ", age='" + age + '\'' +
106                 ", score=" + score +
107                 ", adress='" + adress + '\'' +
108                 '}';
109     }
110 }

 

  • test.java;测试方法,在new readexcelutil 的时候只需要将对象类型与excel文件路径传入构造函数即可,然后调用 readexcelutil的getobjectlist即可得到解析后的所有对象。至于这个对象你可以用任何的对象,你可以换成teacher、orderinfo、userinfo......但是前面提到的:excel第一行的属性字段需要与bean的属性字段一致,否则无法调用目标方法,具体可参见reflectioninitvalue的方法。
 1 package hello;
 2 
 3 import java.util.list;
 4 
 5 import com.hdbs.beans.student;
 6 import com.hdbs.resolver.readexcelutil;
 7 
 8 /**
 9  * @version 1.0.0
10  * @author  cnblogs-windsjune
11  * @date    2018年9月23日 上午1:16:34
12  * 
13  */
14 public class test {
15     public static void main(string[] args) {
16         student student=new student();
17         string filepath="e:/test.xlsx";
18         try {
19             readexcelutil readexcelutil=new readexcelutil(student,filepath);
20             list<object> list=readexcelutil.getobjectslist();
21             for (object object:list){
22                 student test=(student) object;
23                 system.out.println(test.tostring());
24             }
25         } catch (exception e) {
26             e.printstacktrace();
27         }
28     }
29 }

 

表格规范:

 

执行结果:

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网